Java Regex 中matches() 和find() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4450045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:41:49  来源:igfitidea点击:

Difference between matches() and find() in Java Regex

javaregex

提问by Shervin Asgari

I am trying to understand the difference between matches()and find().

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

According to the Javadoc, (from what I understand), matches()will search the entire string even if it finds what it is looking for, and find()will stop when it finds what it is looking for.

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

If that assumption is correct, I cannot see whenever you would want to use matches()instead of find(), unless you want to count the number of matches it finds.

如果这个假设是正确matches()find(),除非您想计算它找到的匹配项的数量,否则我看不到您何时想使用代替。

In my opinion the String class should then have find()instead of matches()as an inbuilt method.

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

So to summarize:

所以总结一下:

  1. Is my assumption correct?
  2. When is it useful to use matches()instead of find()?
  1. 我的假设正确吗?
  2. 什么时候使用matches()而不是有用find()

采纳答案by Sanjay T. Sharma

matchestries to match the expression against the entire string and implicitly add a ^at the start and $at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:

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
*/

123is a substring of a123bso the find()method outputs true. matches()only 'sees' a123bwhich is not the same as 123and thus outputs false.

123是一个子串,a123b所以该find()方法输出真。matches()只有“sees”a123b与“sees”不同123,因此输出false。

回答by khachik

matchesreturn true if the whole string matches the given pattern. findtries to find a substring that matches the pattern.

matches如果整个字符串与给定的模式匹配,则返回 true。find尝试找到与模式匹配的子字符串。

回答by L. Holanda

matches()will only return true if the full string is matched. find()will try to find the nextoccurrence within the substring that matches the regex. Note the emphasis on "the next". That means, the result of calling find()multiple times might not be the same. In addition, by using find()you can call start()to return the position the substring was matched.

matches()如果完整字符串匹配,则仅返回 true。 find()将尝试在与正则表达式匹配的子字符串中找到下一个匹配项。注意对“下一个”的强调。这意味着,find()多次调用的结果可能不一样。此外,通过使用find()您可以调用start()返回子字符串匹配的位置。

final Matcher subMatcher = Pattern.compile("\d+").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + subMatcher.matches());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find());
System.out.println("Found: " + subMatcher.find());
System.out.println("Matched: " + subMatcher.matches());

System.out.println("-----------");
final Matcher fullMatcher = Pattern.compile("^\w+$").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + fullMatcher.find() + " - position " + fullMatcher.start());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());

Will output:

将输出:

Found: false
Found: true - position 4
Found: true - position 17
Found: true - position 20
Found: false
Found: false
Matched: false
-----------
Found: true - position 0
Found: false
Found: false
Matched: true
Matched: true
Matched: true
Matched: true

So, be careful when calling find()multiple times if the Matcherobject was not reset, even when the regex is surrounded with ^and $to match the full string.

因此,find()如果Matcher对象未重置,则在多次调用时要小心,即使正则表达式被包围^$匹配完整字符串也是如此。

回答by L. Holanda

matches();does not buffer, but find()buffers. find()searches to the end of the string first, indexes the result, and return the boolean value and corresponding index.

matches();不缓冲,但find()缓冲。find()首先搜索到字符串的末尾,索引结果,并返回布尔值和对应的索引。

That is why when you have a code like

这就是为什么当你有一个像

1:Pattern.compile("[a-z]");

2:Pattern.matcher("0a1b1c3d4");

3:int count = 0;

4:while(matcher.find()){

5:count++: }

At 4:The regex engine using the pattern structure will read through the whole of your code (index to index as specified by the regex[single character]to find at least one match. If such match is found, it will be indexed then the loop will execute based on the indexed result else if it didn't do ahead calculation like which matches(); does not. The while statement would never execute since the first character of the matched string is not an alphabet.

4:使用模式结构的正则表达式引擎将通读您的整个代码(索引指定的索引regex[single character]以找到至少一个匹配项。如果找到这样的匹配项,它将被索引,然后循环将基于索引结果 else 如果它没有像 which 那样进行提前计算,matches()则不会。while 语句永远不会执行,因为匹配字符串的第一个字符不是字母表。

回答by Sumanth Varada

find()will consider the sub-string against the regular expression where as matches()will consider complete expression.

find()将根据正则表达式考虑子字符串,而 asmatches()将考虑完整表达式。

find()will returns true only if the sub-string of the expression matches the pattern.

find()仅当表达式的子字符串与模式匹配时才返回 true。

public static void main(String[] args) {
        Pattern p = Pattern.compile("\d");
        String candidate = "Java123";
        Matcher m = p.matcher(candidate);

        if (m != null){
            System.out.println(m.find());//true
            System.out.println(m.matches());//false
        }
    }