5

I am using this code to loop through a Matcher and then add each match to a list. For some reason, the find() method is only finding the first 2 out of the 4 matches. I know that the pattern works because I have successfully matched all 4 items using an external regex tester.

Matcher NightQuantities = Pattern.compile('(?mi)(\\d)(?=\\sNight)').matcher(RatesDatesMatcher.group(1));

Integer x = 0;

        while (NightQuantities.find()) //Adds number of nights for each period into list 
        {
            NightQuantitiesList.add(Integer.valueOf(NightQuantities.group(x)));
            System.debug('List input =' + NightQuantities.group(x));
            System.debug('x = ' + x);
            x++;
        } 

I keep getting the error:

"Group index out of bounds (parameter 1): No group 2

1 Answer 1

6

I tested your regular expression on RegexPlanet, and I found that it agrees with the behavior that salesforce is presenting:

Regular Expression  (?mi)(\d)(?=\sNight)
as a Java string    "(?mi)(\\d)(?=\\sNight)"
Replacement 
groupCount()    1

Groups are numerically numbered starting from zero (as all indexing works in Java), so there are two groups: 0 and 1. Group 0 is always the entire match, and group 1 is the next group. You don't have three capture groups here-- you only have 1. (?...) is not a capture group (it merely toggles flags), and (?=...) is not a capture group, because it is merely a zero-length look ahead, which simply means it asserts that those characters are present at that point in the match.

After each find() call, the next match starts at group 0 all over again. So if there's four matches, you need to call find() four times, using group 0 and/or group 1 each time (both groups will actually contain the same information, because (?...) is a zero-length match in all cases).

1
  • Ahhhhh. I was thinking that group(x) was the "match(x)". I have made the alteration to the code and it now runs perfectly! Thank you very much :))! Commented Oct 2, 2015 at 20:31

You must log in to answer this question.

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