繁体   English   中英

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

[英]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);
}

openJDK7的片段

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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