2

Is there a way that I could print the contents of each regex match within a loop? Say I have the following pattern:

1xxxx2xxxx3

If I have a matcher that is (?mi)(\d)...How could I iterate through the matches and print out the contents of each match?

ex) System.debug(match1) //should be 1
    System.debug(match2) //should be 2
    System.debug(match3) //should be 3

1 Answer 1

2

Assuming that your regex is correct you can do the following to iterate over the matches:

Pattern p = Pattern.compile(yourRegex);
Matcher pm = p.matcher(yourString);
if (pm.matches()) {
    for (Integer i = 1; i <= pm.groupCount(); i++) {
        System.debug(pm.group(i));
    }
}

Reference: Matcher Class

2
  • 1
    Thank you. Is there an advantage of using matches() in this scenario as opposed to find()? Commented Oct 2, 2015 at 14:05
  • 1
    Also I thought that groupCount() returned the number of groups in the formula, not the number of matches. I tried a similar loop using groupCount() and it didn't get me very far Commented Oct 2, 2015 at 15:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .