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 statementboolean 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 expressionPattern.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)
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With