Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

regex - Java Pattern Matcher: create new or reset?

Assume a Regular Expression, which, via a Java Matcher object, is matched against a large number of strings:

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
    }
}

In the Java SE 6 JavaDoc for Matcher, one finds the option of reusing the same Matcher object, via the reset(CharSequence) method, which, as the source code shows, is a bit less expensive than creating a new Matcher every time, i.e., unlike above, one could do:

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
    }
}

Should one use the reset(CharSequence) pattern above, or should they prefer to initialize a new Matcher object every time?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

By all means reuse the Matcher. The only good reason to create a new Matcher is to ensure thread-safety. That's why you don't make a public static Matcher m—in fact, that's the reason a separate, thread-safe Pattern factory object exists in the first place.

In every situation where you are sure there's only one user of Matcher at any point in time, it is OK to reuse it with reset.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...