java regex capture group
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));
}
}
Solution 1:
Numbering of subgroups starts with 1, 0 is the full text. Just go till count+1 with your loop.
Solution 2:
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