Java Pattern Matcher:创建新的还是重置?

PNS*_*PNS 21 java regex matcher reset

假设a Regular Expression,通过Java Matcher对象与大量字符串匹配:

String expression = ...; // The Regular Expression
Pattern pattern = Pattern.compile(expression);
String[] ALL_INPUT = ...; // The large number of strings to be matched

Matcher matcher; // Declare but not initialize a Matcher

for (String input:ALL_INPUT)
{
    matcher = pattern.matcher(input); // Create a new Matcher

    if (matcher.matches()) // Or whatever other matcher check
    {
         // Whatever processing
    }
}
Run Code Online (Sandbox Code Playgroud)

Java SE 6 JavaDoc for Matcher中,可以Matcher通过该reset(CharSequence)方法找到重用同一对象的选项,正如源代码所示,该方法比Matcher每次创建新对象要便宜一些,即,与上面不同,可以做:

String expression = ...; // The Regular Expression
Pattern pattern = Pattern.compile(expression);
String[] ALL_INPUT = ...; // The large number of strings to be matched

Matcher matcher = pattern.matcher(""); // Declare and initialize a matcher

for (String input:ALL_INPUT)
{
    matcher.reset(input); // Reuse the same matcher

    if (matcher.matches()) // Or whatever other matcher check
    {
         // Whatever processing
    }
}
Run Code Online (Sandbox Code Playgroud)

应该使用reset(CharSequence)上面的模式,还是应该Matcher每次都初始化一个新对象?

Mar*_*nik 28

一定要重用Matcher.创建新的唯一好理由Matcher是确保线程安全.这就是为什么你不做public static Matcher m- 事实上,这就是Pattern首先存在一个单独的,线程安全的工厂对象的原因.

在您确定Matcher任何时间点只有一个用户的情况下,可以重复使用它reset.

  • 我鼓励您改进这个已有十年历史的答案:) (2认同)