我想知道为什么当提供相同的正则表达式和相同的字符串时,java regexpattern.matcher()和pattern.matches()的结果不同
String str = "hello+";
Pattern pattern = Pattern.compile("\\+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println("I found the text " + matcher.group() + " starting at "
+ "index " + matcher.start() + " and ending at index " + matcher.end());
}
System.out.println(java.util.regex.Pattern.matches("\\+", str));
上面的结果是:
I found the text + starting at index 5 and ending at index 6
false
我发现使用表达式来匹配完整字符串在以下情况下效果很好matches(".*\\+")
.
pattern.matcher(String s)
返回一个Matcher
这样可以find字符串中的模式s
. pattern.matches(String str)
测试,如果整个字符串 (str
) 与模式匹配。
简而言之(只是为了记住区别):
-
pattern.matcher
- 测试字符串是否包含-a pattern
-
pattern.matches
- 测试字符串是否is-a pattern
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)