我想知道为什么java regex pattern.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));
Run Code Online (Sandbox Code Playgroud)
以上结果是:
I found the text + starting at index 5 and ending at index 6
false
Run Code Online (Sandbox Code Playgroud)
我发现使用表达式匹配完整的字符串可以正常工作matches(".*\\+")
.
And*_*s_D 36
pattern.matcher(String s)
返回一个Matcher
可以在String中找到模式的东西s
.pattern.matches(String str)
测试,如果整个String(str
)匹配模式.
简而言之(只是为了记住差异):
pattern.matcher
- 测试字符串是否包含模式pattern.matches
- 测试字符串是否为模式 归档时间: |
|
查看次数: |
59668 次 |
最近记录: |