Alex Rivera | Logout

java regex capture group

Asked 2011-07-28T20:40:06.520
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));
    }
}
Edit
Report

1 Answer

29

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

answered 2011-07-28T20:42:30.403

Your Answer