pattern.matcher()vs pattern.matches() [英] pattern.matcher() vs pattern.matches()

查看:126
本文介绍了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 可以在 code> s 中查找模式。 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 pattern
  • pattern.matches - test if the string is-a pattern

这篇关于pattern.matcher()vs pattern.matches()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆