小编sam*_*jit的帖子

pattern.matcher()vs pattern.matches()

我想知道为什么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(".*\\+").

java regex

31
推荐指数
1
解决办法
6万
查看次数

标签 统计

java ×1

regex ×1