10. JAVA正则
matcher.find()和matcher.matches()的区别
1. matches()
功能:尝试根据模式匹配整个区域
注意:匹配的是整个区域
下面是测试源代码:
//创建指定匹配规则的模型
Pattern pattern = Pattern.compile("ab([1-8]*)f");
//创建匹配器
Matcher matcher = pattern.matcher("ab5625836f");
if(matcher.matches()) {
System.out.println(matcher.start() + " " + matcher.end() + " " + matcher.group());
} else {
System.out.println("没有匹配到!");
}
输出结果:
0 10 ab5625836f
2. find()
功能:尝试查找与该模式匹配的输入序列的下一个子序列。
注意:此方法从该匹配器区域的开始处开始,或者,如果该方法的前一次调用成功,匹配器也成功了,并且没有被重置,在上一次匹配成功后不能被匹配的第一个字符。
下面是测试源代码:
//创建指定匹配规则的模型
Pattern pattern = Pattern.compile("ab([1-8]*)f");
//创建匹配器
Matcher matcher = pattern.matcher("ab2fdsdfdfab348fdfab2333fddd");
int count = 1;
while (matcher.find()) {
System.out.println("第" + count + "组: " + matcher.start() + " " + matcher.end() + " " + matcher.group());
count ++;
};
输出结果:
第1组: 0 4 ab2f
第2组: 10 16 ab348f
第3组: 18 25 ab2333f
3. 一种情况:单独使用find()可以查到,但在matches()之后使用find(),不能查到。
//创建指定匹配规则的模型
Pattern pattern = Pattern.compile("ab([1-8]*)f");
//创建匹配器
Matcher matcher = pattern.matcher("ab5625836f");
if(matcher.matches()) {
System.out.println(matcher.start() + " " + matcher.end() + " " + matcher.group());
} else {
System.out.println("没有匹配到!");
}
if(matcher.find()){
System.out.println(matcher.start() + " " + matcher.end() + " " + matcher.group());
}
find()方法源代码:
public boolean find() {
int nextSearchIndex = last;
if (nextSearchIndex == first)
nextSearchIndex++;
// If next search starts before region, start it at region
if (nextSearchIndex < from)
nextSearchIndex = from;
// If next search starts beyond region then it fails
if (nextSearchIndex > to) {
for (int i = 0; i < groups.length; i++)
groups[i] = -1;
return false;
}
return search(nextSearchIndex);
}
注意第一句代码::int nextSearchIndex = last;
在之前matches()执行后,last=10;所以nextSearchIndex从索引10开始查询,自然就查不到了。
4. 分组匹配
有如下需求:
字符串"<123abc>"
,其中开头结尾是<>
固定格式,中间的内容前半部分是若干数字,后半部分是若干字母,要求分别获取出数字和字母。
关键在于正则表达式必须全局匹配成功才行