0

Can some explain the following output for java regex:(CASE 1)

   String s = "topcoder is "

            String p = "(top|coder)+";
            Pattern pttrn = Pattern.compile(p);
            Matcher m = pttrn.matcher(s);
            while(m.find()){
                System.out.println("group count: " + m.groupCount());
                for (int i = 1; i <= m.groupCount(); i++) {
                    System.out.println("Found : \"" + m.group(i) + "\" as group " + i);
                }
                System.out.println("Zeroth group:" + m.group(0));
            }

produces following output:

group count: 1

Found : "coder" as group 1

Zeroth group:topcoder

Where the following code: (CASE 2)

        String s = "topcoder is ";
        String p = "(top|coder)";
        Pattern pttrn = Pattern.compile(p);
        Matcher m = pttrn.matcher(s);
        while(m.find()){
            System.out.println("group count: " + m.groupCount());
            for (int i = 1; i <= m.groupCount(); i++) {
                System.out.println("Found : \"" + m.group(i) + "\" as group " + i);
            }
            System.out.println("Zeroth group:" + m.group(0));
        }

produces following output:

group count: 1

Found : "top" as group 1

Zeroth group:top

group count: 1

Found : "coder" as group 1

Zeroth group:coder

Why isn't there are match for top in CASE 1 ? How is + affecting the matching for alternation (|) ?

1
  • 1
    When you repeat a capture group with a quantifier, the previous capture is overwritten by the next. Commented Jun 6, 2015 at 21:55

1 Answer 1

2

When using a capturing group that repeats, ie. because of a quantifier, the Matcher will only capture the last match.

You can wrap the entire repeated capturing group in its own capturing group to extract each match

String p = "((top|coder)+)";

This is explained in regex101.

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

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.