Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse Pattern instance in Java

Tags:

java

regex

My question is, if it is possible to reuse the compiled pattern using Pattern.compile( ) when used with String.matches( )?

Because, in the docs it says,

A matches method is defined by this class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statement

boolean b = Pattern.matches("a*b", "aaaaab"); 

is equivalent to the three statements above, though for repeated matches it is less efficient since it does not allow the compiled pattern to be reused.

http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

It only says that when you use Pattern.matches it becomes less efficient. And I got confused on this part:

An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression

Pattern.matches(regex, str)

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#matches(java.lang.String)

So I am not sure if String.matches uses Pattern.matches and because of that I cannot reuse the compiled pattern again. I was actually planning to set the compiled pattern as a constant (for optimization purposes)

like image 754
Richeve Bebedor Avatar asked Dec 26 '22 10:12

Richeve Bebedor


1 Answers

Pattern.matches() method is a static method so it cannot be used if you want to reuse a compiled pattern. A compiled pattern is an instance of Pattern class. Pattern.matches() compiles your regex every time it's used.

You can reuse your compiled pattern by storing an instance of Pattern class, e.g.:

Pattern pattern = Pattern.compile("^[a-z]+$", Pattern.CASE_INSENSITIVE); // you can store this instance

You can then get a matcher for this pattern each time you want to use it

Matcher m = pattern.matcher("Testing");
like image 109
Szymon Avatar answered Jan 08 '23 11:01

Szymon