[英]Java regex, matches and find
我仍然在理解match()和find()的区别方面仍然遇到问题,这里的代码
final Matcher subMatcher = Pattern.compile("\\d+").matcher("123");
System.out.println("Found : " + subMatcher.matches());
System.out.println("Found : " + subMatcher.find());
输出是
Found : true Found : false
什么我了解比赛,从这个找到答案 ,是匹配()试图同时查找()只尝试匹配下一个匹配的字符串整个字符串匹配,并且匹配增添了^和$元字符开始和如果我们没有多次使用它,则begin和find()可以有不同的结果,但是这里123仍然是一个子字符串,第二个输出应该为true。 如果我注释掉第二行,则确实显示输出为true
当您调用matches()
, Matcher
已经搜索到匹配项(整个String
)。 调用find
Matcher
将在当前匹配之后尝试再次查找模式,但是由于匹配整个String
的匹配之后没有剩余字符,因此find
返回false
。
要再次搜索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.