简体   繁体   中英

Pattern.matches vs string.matches(“regex”)

What is better performance wise:
string.matches("regex")
or
Pattern.compile("regex").matches(string).find() ?

What I am referring to is matching through String.java 's matches() , or API in Pattern.java

Implementation of String.matches(String regex) :

public boolean matches(String regex) {
    return Pattern.matches(regex, this);
}

Implementation of Pattern.matches(String regex, CharSequence input) :

public static boolean matches(String regex, CharSequence input) {
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(input);
    return m.matches();
}

Conclusion: str.matches(regex) is exactly the same as Pattern.compile(regex).matcher(str).matches() .

Note: Same as matches() , not same as find() .

Using Pattern.compile() is better/required if:

  • You need access to the Matcher .
    Eg you need the result of capture groups.

  • You do the same matches(regex) call many times.
    Only compiling the regex pattern once improves performance.

It depends on whether you will be reusing the regex. If you do, it is better to compile it only once. The matches function in String is defined in terms of Pattern.matches :

public boolean matches(String regex) {
    return Pattern.matches(regex, this);
}

Snippet from openJDK7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM