matches()只有在匹配完整字符串时才返回true。find()会试图找到下一个匹配正则表达式的子字符串中的事件。注意强调“下一个”。这意味着,调用的结果find()多次可能是不一样的。此外,通过使用find()你可以打电话start()若要返回子字符串的位置,则匹配子字符串。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());
将产出:Found: false
Found: true - position 4
Found: true - position 17
Found: true - position 20
Found: false
Found: false
Matched: false
-----------
Found: true - position 0
Found: false
Found: false
Matched: true
Matched: true
Matched: true
Matched: true
所以,打电话时要小心find()如果Matcher对象没有重置,即使regex被包围时也是如此。^和$来匹配完整的字符串。