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));
    }
}
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561

2 Answers2

29

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

yankee
  • 38,872
  • 15
  • 103
  • 162
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

duduamar
  • 3,816
  • 7
  • 35
  • 54
  • 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). – william.berg Mar 22 '13 at 16:39