如果完整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。