Java Regex中matches()和find()的区别 [英] Difference between matches() and find() in Java Regex
问题描述
根据Javadoc,(据我所知),matches()
将搜索整个字符串,即使它找到了它要查找的内容,并且 find()
会在找到要查找的内容时停止.
According to the Javadoc, (from what I understand), matches()
will search the entire string even if it finds what it is looking for, and find()
will stop when it finds what it is looking for.
如果这个假设是正确的,我看不出你何时想要使用 matches()
而不是 find()
,除非你想计算匹配的数量它找到了.
If that assumption is correct, I cannot see whenever you would want to use matches()
instead of find()
, unless you want to count the number of matches it finds.
在我看来,String 类应该将 find()
而不是 matches()
作为内置方法.
In my opinion the String class should then have find()
instead of matches()
as an inbuilt method.
总结一下:
- 我的假设是否正确?
- 什么时候用
matches()
代替find()
有用?
- Is my assumption correct?
- When is it useful to use
matches()
instead offind()
?
推荐答案
matches
尝试将表达式与整个字符串进行匹配,并在开头隐式添加 ^
$
在您的模式末尾,这意味着它不会查找子字符串.因此,此代码的输出:
matches
tries to match the expression against the entire string and implicitly add a ^
at the start and $
at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:
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()
方法输出真.matches()
仅看到" a123b
与 123
不同,因此输出 false.
123
is a substring of a123b
so the find()
method outputs true. matches()
only 'sees' a123b
which is not the same as 123
and thus outputs false.
这篇关于Java Regex中matches()和find()的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!