Java Matcher对象中find()与matches()的区别

439 阅读1分钟

find()与matches()的区别

find():字符串某个部分匹配上模式就会返回true

matches():整个字符串匹配上模式才返回true,否则false

观察一个现象

Pattern compile = Pattern.compile("abc");
Matcher matcher = compile.matcher("abc");
if (matcher.matches()) {                               // true
    System.out.println("matches " + matcher.group());  // matches abc
}
while (matcher.find()) {                               // false
    System.out.println("find " + matcher.group());
}
Pattern compile = Pattern.compile("abc");
Matcher matcher = compile.matcher("abc");
while (matcher.find()) {                              // true
    System.out.println("find " + matcher.group());    // find abc
}
if (matcher.matches()) {                              // true
    System.out.println("matches " + matcher.group()); // matches abc
}

原因:

find: Attempts to find the next subsequence of the input sequence that matches the pattern.
如果该方法的先前调用成功且此后匹配器尚未重置,则在与先前匹配不匹配的第一个字符处开始

matchs: Attempts to find the next subsequence of the input sequence that matches the pattern.
重新尝试整个匹配

解决方法

Pattern compile = Pattern.compile("abc");
Matcher matcher = compile.matcher("abc");
if (matcher.matches()) {
    System.out.println("matches " + matcher.group());    // matches abc
}
matcher = compile.matcher("abc");
while (matcher.find()) {
    System.out.println("find " + matcher.group());      // find abc
}
Pattern compile = Pattern.compile("abc");
Matcher matcher = compile.matcher("abc");
if (matcher.matches()) {
    System.out.println("matches " + matcher.group());   // matches abc
}
matcher.reset();
while (matcher.find()) {
    System.out.println("find " + matcher.group());      // find abc
}

参考

Java正则表达式中Matcher类的find方法多次调用的匹配问题