分组匹配(提取子串). :一个任意字符
w : 一个常用字符(字母,数字,下划线)
s : 一个空格
d : 数字
D : 非数字
* : 任意个字符,可以是 0
+ : 至少一个
? : 0个或1个
{n}
^ 表示开头 $表示结尾
[0-9a-fA-F]
[^0-9]{3} : 不是0-9
java | php
Pattern p = Pattern.compile(regex)
Matcher m = p.matcher()
m.matches()
m.group(1)
String regex = "(\d{3,4})-(\d{6,8})";
String tel = "010-12345678";
// pattern 模式
Pattern p = Pattern.compile(regex);
// matcher 匹配器
Matcher m = p.matcher(tel);
if (m.matches()){
String g1 = m.group(1);
String g2 = m.group(2);
System.out.println("g1 = " + g1);
System.out.println("g2 = " + g2);
System.out.println(m.group(0));
}else {
System.out.println("matcher failed");
}
正则表达式默认使用贪婪匹配,任何一个规则,他总是尽可能的向后匹配更多的字符,
非贪婪匹配,需要在规则后面加一个?
d??:第一个问号是0或1个,第二个是非贪婪匹配,非贪婪匹配会尽可能的少匹配,会匹配0个数字
m.find()
m.start()
m.end()
public void test05 (){
String s = "the quick brown fox jumps over the lazy dog.";
Pattern p = Pattern.compile("\wo\w");
Matcher m = p.matcher(s);
// 查找字符
while(m.find()){
String sub = s.substring(m.start(), m.end());
System.out.println(sub);
}
}
public void test06 (){
String s = "The quicktt brown fox jumps over the lazy dog.";
String r = s.replaceAll("\s+", " ");
System.out.println(r);
}
反向引用
public void test07 (){
String s = "the quick brown fox jumps over the lazy dog.";
String r = s.replaceAll("\s([a-z]{4})\s", " $1 ");
System.out.println(r);
}
替换
m.appendReplacement() : 将上次替换的位置到这次替换位置之间的字符串 加上替换的字符串 ,一起追加到StringBuffer中
m.appendTail() : 将最后一次匹配到内容之后的字符串,,追加到StringBuffer中
public void test08 (){
String s = "Hello, ${name}! You are learning ${lang}!...";
HashMap map = new HashMap<>();
map.put("name","Bob");
map.put("lang","Java");
Pattern p = Pattern.compile("\$\{(\w+)\}");
Matcher m = p.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()){
// 将上次替换的位置到这次替换位置之间的字符串 加上替换字符串 一起追加到StringBuffer里
m.appendReplacement(sb,map.get(m.group(1)));
}
// 把最后一次匹配到内容之后的字符串 追加到StringBuffer中
m.appendTail(sb);
System.out.println(sb);
}
引用:https://www.liaoxuefeng.com/wiki/1252599548343744/1306046817632290
https://blog.csdn.net/fly_duck/article/details/108733966



