[SalesForce] “No match found” when using Regex in Apex

I've got a regex query[(\d+)-(\d+)-(\d+)] but whenever I try to access any of the groups it gives me the error "No match found" even though when I run .groupCount() it gives back 3. Double checked the regex query with Regex Builder and a "Java Regex Tester".

Apex:

    system.debug(book_date);//12-21-2013
    Pattern p = Pattern.compile('(\\d+)-(\\d+)-(\\d+)');
    Matcher pm = p.matcher( book_date );
    system.debug(p);
    system.debug(pm);
    system.debug(pm.groupCount());//3

    system.debug(pm.group(0));// <!-- Fails here
    system.debug(pm.group(1));
    system.debug(pm.group(2));
    system.debug(pm.group(3));

Any thoughts on what the issue could be?

Regex working proof:
Regex Java Proof

Best Answer

You need to do a pm.matches() first to make it match the region against the pattern. See my comments in the code.

system.debug(book_date);//12-21-2013
Pattern p = Pattern.compile('(\\d+)-(\\d+)-(\\d+)');
Matcher pm = p.matcher( book_date );
system.debug(p);
system.debug(pm);
system.debug(pm.groupCount()); // This just counts the number groups in your regex, not the number of matches

if (pm.matches()) {
    system.debug(pm.group(1)); //12
    system.debug(pm.group(2)); //21
    system.debug(pm.group(3)); //2013
}
Related Topic