Java正則表示式Matcher的find()和matches()方法不同
阿新 • • 發佈:2019-01-31
1、直接上結論:
find()方法在部分匹配時和完全匹配時返回true,匹配不上返回false;
matches()方法只有在完全匹配時返回true,匹配不上和部分匹配都返回false。
2、測試該結論的例子如下:
String regex = "own\\.png";String input= "down.png";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
System.out.println(m.matches());//false
m.reset();
System.out.println(m.find());//true
String regex = "down\\.png";
String input = "down.png";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
System.out.println(m.matches());//true
m.reset();
System.out.println(m.find());//true
3、驗證該結論需要檢視原始碼。
find()方法註釋最後部分對return true進行解釋: if, and only if, a subsequence of the input sequence matches this matcher's pattern,根據這句解釋整個input也算是a subsequence;
matches()方法註釋最後部分對return true進行解釋: if, and only if, the entire region sequence matches this matcher's pattern。