Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
799 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...