小编典典

Java Regex中match()和find()之间的区别

java

我想明白之间的差别matches()find()

根据Javadoc,(据我了解),matches()即使找到了所要查找的内容,它也会搜索整个字符串,并find()在找到所要查找的内容时停止。

如果这个假设是正确的,我看不到,只要你想使用matches()的,而不是find(),除非你想指望它找到匹配的数量。

在我看来,String类应该具有find()而不是matches()作为内置方法。

总结一下:

  1. 我的假设正确吗?
  2. 什么时候matches()代替有用find()

阅读 459

收藏
2020-02-25

共1个答案

小编典典

matches尝试将表达式与整个字符串匹配,^$在模式的开头和结尾隐式添加a ,这意味着它将不查找子字符串。因此,此代码的输出:

public static void main(String[] args) throws ParseException {
    Pattern p = Pattern.compile("\\d\\d\\d");
    Matcher m = p.matcher("a123b");
    System.out.println(m.find());
    System.out.println(m.matches());

    p = Pattern.compile("^\\d\\d\\d$");
    m = p.matcher("123");
    System.out.println(m.find());
    System.out.println(m.matches());
}

/* output:
true
false
true
true
*/

123是的子字符串,a123b因此该find()方法输出truematches()只能“看到” a123b,它与不相同123,因此输出false。

2020-02-25