1 matces() lookingAt() find()区别
// matches()对整个字符串进行匹配,只有整个字符串都匹配了才返回true
Pattern p=Pattern.compile("\d+");
Matcher m=p.matcher("22bb23");
m.matches();//返回false,因为bb不能被d+匹配,导致整个字符串匹配未成功.
Matcher m2=p.matcher("2223");
m2.matches();//返回true,因为d+匹配到了整个字符串
// lookingAt()对前面的字符串进行匹配,只有匹配到的字符串在最前面才返回true
Pattern p1=Pattern.compile("\d+");
Matcher m3=p1.matcher("22bb23");
m.lookingAt();//返回true,因为d+匹配到了前面的22
Matcher m4=p1.matcher("aa2223");
m2.lookingAt();//返回false,因为d+不能匹配前面的aa
// find()对字符串进行匹配,匹配到的字符串可以在任何位置.
Pattern p2=Pattern.compile("\d+");
Matcher m5=p2.matcher("22bb23");
m.find();//返回true
Matcher m6=p2.matcher("aa2223");
m2.find();//返回true
Matcher m7=p2.matcher("aa2223bb");
m3.find();//返回true
Matcher m8=p2.matcher("aabb");
m4.find();//返回false
Pattern pattern = Pattern.compile(".*?o");
Matcher matcher = pattern.matcher("zoboco");
while(matcher.find()){
System.out.println(matcher.group(0));
}
运行结果:
zo
bo
co
java 正则表达式中的分组
正则表达式的分组在java中是怎么使用的.
start(),end(),group()均有一个重载方法它们是start(int i),end(int i),group(int i)专用于分组操作,Mathcer类还有一个groupCount()用于返回有多少组.
Java代码示例:
Pattern p=Pattern.compile("([a-z]+)(\d+)"); 匹配模式中一个括号就是一组
Matcher m=p.matcher("aaa2223bb");
m.find(); //匹配aaa2223
m.groupCount(); //返回2,因为有2组
m.start(1); //返回0 返回第一组匹配到的子字符串在字符串中的索引号
m.start(2); //返回3
m.end(1); //返回3 返回第一组匹配到的子字符串的最后一个字符在字符串中的索引位置.
m.end(2); //返回7
m.group();//返回aaa2223
m.group(1); //返回aaa,返回第一组匹配到的子字符串
m.group(2); //返回2223,返回第二组匹配到的子字符串