Thursday, 13 October 2011

Note to self when using java regex - always call Matcher.matches() so that text matching actually happens

The general pattern of usage is:

1. regexString = [REGEX]
2. final Pattern p = Pattern.compile(regexString);
3. final Matcher matcher = p.matcher(text_to_match);
4. matcher.matches() 

DO NOT FORGET to call Matcher.matches().

Otherwise you will get messages like:

java.lang.IllegalStateException: No match found

and you'll be wondering why because you have confirmed that the regex itself is correct. ( and are useful tools for doing this quickly)

REMEMBER: call .matches() so that our Matcher actually performs the matching!

Just wasted 10 minutes wondering what I was doing wrong.

No comments: