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)); 

以上结果是:

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

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

pattern.matcher(String s)返回一个可以在String中找到模式的Matcherpattern.matches(String str)测试,如果整个String( str )与模式匹配。

简而言之(只是为了记住差异):

  • pattern.matcher – 测试字符串是否包含模式
  • pattern.matches – 测试字符串是否为模式

Matcher.find()尝试查找与模式匹配的输入序列的下一个子序列。

Pattern.matches(String regex, CharSequence input)将正则表达式编译为Matcher并返回Matcher.matches()

Matcher.matches尝试将整个区域(字符串)与模式(Regex)进行匹配。

因此,在您的情况下, Pattern.matches("\\+", str)返回false,因为str.equals("+")为false。

从Javadoc中,查看if,仅当整个区域部分

  /** * Attempts to match the entire region against the pattern. * * 

If the match succeeds then more information can be obtained via the * start, end, and group methods.

* * @return true if, and only if, the entire region sequence * matches this matcher's pattern */ public boolean matches() { return match(from, ENDANCHOR); }

因此,如果您的String只是“+”,那么您将获得真实的结果。

matches尝试将表达式与整个字符串进行匹配。 意思是,它检查整个字符串是否是patern。 在概念上认为它是这样的,它隐含地在开始时添加^,在模式的末尾添加$。

对于,String str =“hello +”,如果希望matches()返回true,则需要具有类似“。 \ + ”的模式

我希望这能回答你的问题。

Pattern.matches正在测试整个String,在你的情况下你应该使用:

  System.out.println(java.util.regex.Pattern.matches(".*\\+", str)); 

含义任何字符串和+符号

我认为你的问题应该是“我什么时候应该使用Pattern.matches()方法?”,答案是“从不”。 你期望它返回一个匹配的子串的数组,比如.NET的Matches方法吗? 这是一个非常合理的期望,但不,Java没有那样的东西。

如果你只想做一个快速和肮脏的匹配,在任一端用.*装饰正则表达式,并使用字符串自己的matches()方法:

 System.out.println(str.matches(".*\\+.*")); 

如果要提取多个匹配项,或者之后访问有关匹配项的信息,请创建一个Matcher实例并使用方法,就像在问题中一样。 Pattern.matches()只不过是一个浪费的机会。

 Matcher matcher = pattern.matcher(text); 

在这种情况下,将返回匹配器对象实例,该实例通过解释模式对输入文本执行匹配操作。 然后我们可以使用matcher.find()来匹配no。 来自输入文本的模式。

 (java.util.regex.Pattern.matches("\\+", str)) 

这里,将隐式创建匹配器对象,并返回一个布尔值,它将整个文本与模式匹配。 这将与String中的str.matches(regex)函数相同。

相当于java.util.regex.Pattern.matches("\\+", str)将是:

 Pattern.compile("\\+").matcher(str).matches(); 

方法find将在字符串中找到第一次出现的模式。