[英]Java regex, matches and find
I am still having problems understanding difference in matches() and find(), here the code 我仍然在理解match()和find()的区别方面仍然遇到问题,这里的代码
final Matcher subMatcher = Pattern.compile("\\d+").matcher("123");
System.out.println("Found : " + subMatcher.matches());
System.out.println("Found : " + subMatcher.find());
Output is 输出是
Found : true Found : false
Of what I understand about matches and find from this answer , is that matches() tries to match the whole string while find() only tries to match the next matching substring, and the matcher adds a ^ and $ meta-character to start and beginning and the find() can have different results if we use it multiple no of times, but here still 123 remains a substring, and the second output should be true. 什么我了解比赛,从这个找到答案 ,是匹配()试图同时查找()只尝试匹配下一个匹配的字符串整个字符串匹配,并且匹配增添了^和$元字符开始和如果我们没有多次使用它,则begin和find()可以有不同的结果,但是这里123仍然是一个子字符串,第二个输出应该为true。 If i comment out the second line then it does shows output as true 如果我注释掉第二行,则确实显示输出为true
When you call matches()
, the Matcher
already searches for a match (the whole String
). 当您调用matches()
, Matcher
已经搜索到匹配项(整个String
)。 Calling find
the Matcher
will try to find the pattern again after the current match, but since there are no characters left after a match that matches the entire String
, find
returns false
. 调用find
Matcher
将在当前匹配之后尝试再次查找模式,但是由于匹配整个String
的匹配之后没有剩余字符,因此find
返回false
。
To search the String
again, you'd need to create a new Matcher
or call reset()
: 要再次搜索String
,您需要创建一个新的Matcher
或调用reset()
:
final Matcher subMatcher = Pattern.compile("\\d+").matcher("123");
System.out.println("Found : " + subMatcher.matches());
subMatcher.reset();
System.out.println("Found : " + subMatcher.find());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.