0
votes

Is it possible to find all groups in a regular expression that match a specific part of a String?

    Pattern pattern = Pattern.compile("(green trousers)|(green\\s+t)");
    Matcher matcher = pattern.matcher("my beautiful green trousers are red!");
    while (matcher.find()) {
        for (int i = 1; i <= matcher.groupCount(); i++) {
            if (matcher.group(i) != null) {
                System.out.println("group " + i + " matched");
            }
        }
    }

This example only returns the first group as matching, but I also interested in the fact that the second group matches too.

2
No, that's not how regex works. You would have to check 2 different patterns to see if they both match.Sebastian Proske

2 Answers

3
votes

There's no direct way to do this, a regular expression will consume the string from left to right until it finds a match.

Using | means it will first check for the first alternative, if that doesn't match it backtracks and tries the second alternative. In this case (green trousers) matches, so the searching stops and the match is returned.

0
votes

There's no way to check all cases within a single regular expression, however, there are constructs that allow you to check if more than one subpattern matches for a particular substring, and these are so called »zero width assertions« (see here, under »Special constructs«)

Example:

"(?=[ab]{5})[bc]{5}"

will only match on bbbbb