Java Regex中matches()和find()之间的区别 [英] Difference between matches() and find() in Java Regex
问题描述
I am trying to understand the difference between matches()
and find()
.
根据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
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 $的子字符串c $ c>所以
find()
方法输出为true。 matches()
只有'看' a123b
这与 123 $不同c $ c>因此输出错误。
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屋!