-1

String has a convenient method matches(String regex). But I am about to check about 10-100 values for match. I don't think it's very effective to let Java compile the pattern for every call. Instead, I'd like to cache parsed Pattern and use that.

But how can I, staying effective as much as possible, use Pattern object along with String to produce boolean indicating that the string matches the pattern?

public static boolean patternMatches(String tested, Pattern regex) {
   ???
}

Second reason why I want to do this is that I already have a method that takes string and retrieves literal string matchs:

public MyClass[] findMatches(String substring) {
  ...
}

So I wanted to make an overload:

public MyClass[] findMatches(Pattern regex) {
  ...
}
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • 1
    Related: http://stackoverflow.com/questions/1720191/java-util-regex-importance-of-pattern-compile – Tomalak May 09 '15 at 03:24
  • 3
    Did you check the [documentation](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)? Because how to do what you want to do is one of the first things it shows. – user2357112 May 09 '15 at 03:25
  • @user2357112 No, I checked the guides regarding pattern and they mentioned no such thing. I figured it out by looking at the `Patter.matches(String, String)` source code. – Tomáš Zato May 09 '15 at 10:56
  • It's right there in the "typical invocation sequence". – user2357112 May 09 '15 at 10:59
  • @user2357112 Reading post carefully before replying is something I'd expect 50k rep user to manage already. I said I looked at the [online] *guides*. I started my sentence with *No*, indicating "*no, I didn't check the javadoc*". I checked the javadoc now, though I already knew the answer, and I see the answer was there. Is that clear now? – Tomáš Zato May 09 '15 at 11:03

1 Answers1

0

Pattern has a method getMatcher which returns an object describing results of the match.

Pattern pattern = Pattern.compile("pattern");
Matcher matcher = pattern.matcher("Matched string.");
boolean matches = matcher.matches();

Therefore my method would be:

public static boolean patternMatches(String tested, Pattern regex) {
  return regex.matcher(tested).matches();
}
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778