pattern.matcher()vs pattern.matches() [英] pattern.matcher() vs pattern.matches()
问题描述
我想知道为什么java regex pattern.matcher()和pattern.matches()的结果在提供相同的正则表达式和相同的字符串时不同
I am wondering why the results of the java regex pattern.matcher() and pattern.matches() differ when provided the same regular expression and same string
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
我发现在匹配(。* \\ +)
的情况下,使用表达式匹配完整字符串可以正常工作。
I found that using an expression to match the full string works fine in case of matches(".*\\+")
.
推荐答案
pattern.matcher(String s)
返回 Matcher
可以在 pattern.matches(String str)
测试,如果整个String( str
)与模式匹配。
pattern.matcher(String s)
returns a Matcher
that can find patterns in the String s
. pattern.matches(String str)
tests, if the entire String (str
) matches the pattern.
简而言之(只是为了记住差异):
In brief (just to remember the difference):
-
模式.matcher
- 测试字符串是否包含-a 模式 -
pattern.matches
- 测试字符串是-a 模式
pattern.matcher
- test if the string contains-a patternpattern.matches
- test if the string is-a pattern
这篇关于pattern.matcher()vs pattern.matches()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!