0

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.

1
  • 2
    No, that's not how regex works. You would have to check 2 different patterns to see if they both match. Commented Jul 6, 2016 at 10:41

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.