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


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


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++) {

Reference: Matcher Class

  • 1
    Thank you. Is there an advantage of using matches() in this scenario as opposed to find()? 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 Oct 2, 2015 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.