根据Javadoc(根据我的理解),matches()即使它找到了它正在寻找的东西,它也会搜索整个字符串,并find()在它找到它所寻找的内容时停止.
如果这个假设是正确matches()的find(),除非你想要计算它找到的匹配数,否则我无法看到你想要使用的代替.
在我看来,String类应该具有find()而不是matches()作为内置方法.
总结一下:
matches()而不是find()?San*_*rma 286
matches尝试将表达式与整个字符串进行匹配,^并$在模式的开头和结尾隐式添加a ,这意味着它不会查找子字符串.因此,此代码的输出:
public static void main(String[] args) throws ParseException {
Pattern p = Pattern.compile("\\d\\d\\d");
Matcher m = p.matcher("a123b");
System.out.println(m.find());
System.out.println(m.matches());
p = Pattern.compile("^\\d\\d\\d$");
m = p.matcher("123");
System.out.println(m.find());
System.out.println(m.matches());
}
/* output:
true
false
true
true
*/
Run Code Online (Sandbox Code Playgroud)
123是一个子串,a123b所以find()方法输出true.matches()只有'看'与a123b它不相同123,因而输出错误.
kha*_*hik 76
matches如果整个字符串与给定模式匹配,则返回true.find尝试查找与模式匹配的子字符串.
L. *_*nda 57
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());
Run Code Online (Sandbox Code Playgroud)
将输出:
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未重置对象,则多次调用时要小心,即使正则表达式被包围^并$匹配完整字符串也是如此.
find()将考虑针对正则表达式的子字符串,matches()将视为完整表达式。
find() 仅当表达式的子字符串与模式匹配时才返回true。
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d");
String candidate = "Java123";
Matcher m = p.matcher(candidate);
if (m != null){
System.out.println(m.find());//true
System.out.println(m.matches());//false
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
185006 次 |
| 最近记录: |