我试图理解 matches()
之间的区别和 find()
.
根据Javadoc,(据我了解),matches()
将搜索整个字符串,即使它找到了它要查找的内容,而find()
将在找到它要查找的内容时停止。
如果这个假设是正确的,我看不到您何时想使用 matches()
而不是 find()
,除非您想计算它找到的匹配项的数量。
在我看来,String 类应该有 find()
而不是 matches()
作为内置方法。
总结一下:
- 我的假设正确吗?
- 什么时候使用
matches()
而不是find()
有用?
最佳答案
matches
尝试将表达式与整个字符串进行匹配,并在模式的开头隐式添加 ^
并在模式末尾添加 $
,这意味着它不会查找子字符串。因此这段代码的输出是:
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
*/
123
是 a123b
的子字符串,因此 find()
方法输出 true。 matches()
仅“看到”a123b
,它与 123
不同,因此输出 false。
关于java - Java 正则表达式中 matches() 和 find() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33861628/