Pattern.matches vs string.matches("regex")

dmi*_*inn 2 java regex

什么是更好的表现明智:
string.matches("regex")

Pattern.compile("regex").matches(string).find()

我所指的是通过String.java's' matches()或API 匹配Pattern.java

And*_*eas 5

执行String.matches(String regex):

public boolean matches(String regex) {
    return Pattern.matches(regex, this);
}
Run Code Online (Sandbox Code Playgroud)

执行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();
}
Run Code Online (Sandbox Code Playgroud)

结论: str.matches(regex)完全一样Pattern.compile(regex).matcher(str).matches().

注意:与...相同matches(),不一样find().

在以下情况下使用Pattern.compile()更好/更

  • 你需要访问Matcher.
    例如,您需要捕获组的结果.

  • matches(regex)多次做同样的电话.
    仅编译regex模式一次可以提高性能.