gpt4 book ai didi

java - pattern.matcher() 和 pattern.matches()

转载 作者:IT老高 更新时间:2023-10-28 21:06:02 26 4
gpt4 key购买 nike

我想知道为什么当提供相同的正则表达式和相同的字符串时,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));

上面的结果是:

I found the text + starting at index 5 and ending at index 6
false

我发现在 matches(".*\\+") 的情况下,使用表达式匹配完整字符串可以正常工作。

最佳答案

pattern.matcher(String s) 返回一个 Matcher,它可以在字符串 s找到模式。 pattern.matches(String str) 测试整个字符串 (str) 是否与模式匹配。

简而言之(只是为了记住区别):

  • pattern.matcher - 测试字符串是否 contains-a 模式
  • pattern.matches - 测试字符串是否为 is-a 模式

关于java - pattern.matcher() 和 pattern.matches(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3862917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com