23

I am trying to capture the right part after the : using java expr, but in the following code, the printed capture group is the whole string, what's wrong?

String s ="xyz: 123a-45";   
String patternStr="xyz:[ \\t]*([\\S ]+)";
Pattern p = Pattern.compile(patternStr);
Matcher m = p.matcher(s);
//System.err.println(s);
if(m.find()){
    int count = m.groupCount();
    System.out.println("group count is "+count);
    for(int i=0;i<count;i++){
        System.out.println(m.group(i));
    }
}

2 Answers 2

29

Numbering of subgroups starts with 1, 0 is the full text. Just go till count+1 with your loop.

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

1 Comment

More precisely, change the for loop condition to i<=count.
1

This is because group's indices are starting with 1. Group 0 is the entire pattern.

From the JavaDoc: "Capturing groups are indexed from left to right, starting at one. Group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group()." See more here

1 Comment

I think the confusion over this stems from the fact that the doc has muddled "indexing" (always from 0) with "numbering" (from whatever value you like).

Your Answer

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