如果完整string匹配, matches()将只返回true。 find()会尝试find匹配正则expression式的子string中的下一个匹配项。 注意强调“下一个”。 这意味着,多次调用find()的结果可能不一样。 另外,通过使用find()你可以调用start()来返回子string匹配的位置。
final Matcher subMatcher = Pattern.compile("\\d+").matcher("skrf35kesruytfkwu4ty7sdfs"); System.out.println("Found: " + subMatcher.matches()); System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start()); System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start()); System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start()); System.out.println("Found: " + subMatcher.find()); System.out.println("Found: " + subMatcher.find()); System.out.println("Matched: " + subMatcher.matches()); System.out.println("-----------"); final Matcher fullMatcher = Pattern.compile("^\\w+$").matcher("skrf35kesruytfkwu4ty7sdfs"); System.out.println("Found: " + fullMatcher.find() + " - position " + fullMatcher.start()); System.out.println("Found: " + fullMatcher.find()); System.out.println("Found: " + fullMatcher.find()); System.out.println("Matched: " + fullMatcher.matches()); System.out.println("Matched: " + fullMatcher.matches()); System.out.println("Matched: " + fullMatcher.matches()); System.out.println("Matched: " + fullMatcher.matches());
会输出:
发现:错误
发现:真实 - 位置4
发现:真实的位置17
find:真实的位置20
发现:错误
发现:错误
匹配:错误
-----------
find:真实 - 位置0
发现:错误
发现:错误
匹配:是的
匹配:是的
匹配:是的
匹配:是的
所以,如果Matcher对象没有被重置,那么多次调用find()时要小心,即使正则expression式被^和$包围以匹配完整的string。