什么是更好的表现明智:
string.matches("regex")
或
Pattern.compile("regex").matches(string).find()
?
我所指的是通过String.java's' matches()或API 匹配Pattern.java
执行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模式一次可以提高性能.