![](/img/trans.png)
[英]How to use Pattern.matches with regex to filter unwanted characters in a string
[英]Pattern.matches vs string.matches(“regex”)
什么是更好的性能明智的选择:
string.matches("regex")
要么
Pattern.compile("regex").matches(string).find()
吗?
我指的是通过String.java
matches()
或Pattern.java
API进行matches()
String.matches(String regex)
:
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
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();
}
结论: str.matches(regex)
与 Pattern.compile(regex).matcher(str).matches()
。
注意:与matches()
相同,与find()
。
如果满足以下条件,则最好使用Pattern.compile()
:
您需要访问Matcher
。
例如,您需要捕获组的结果。
您多次进行相同的matches(regex)
调用。
仅编译一次regex
模式即可提高性能。
这取决于您是否将重用正则表达式。 如果这样做,最好只编译一次。 本matches
在函数String
中来定义Pattern.matches
:
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.