Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 718
PNS Avatar asked Jul 09 '12 08:07

PNS


People also ask

How does pattern and matcher work in Java?

Java For Testers The matcher() method of this class accepts an object of the CharSequence class representing the input string and, returns a Matcher object which matches the given string to the regular expression represented by the current (Pattern) object.

Is pattern matcher thread safe?

You obtain a Matcher object by invoking the matcher() method on a Pattern object. The Instances of this class are not safe for use by multiple concurrent threads.

How does matcher group work Java?

Java Matcher group() MethodThe group method returns the matched input sequence captured by the previous match in the form of the string. This method returns the empty string when the pattern successfully matches the empty string in the input.


1 Answers

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.

like image 94
Marko Topolnik Avatar answered Oct 10 '22 09:10

Marko Topolnik