Tim AtLee Tim AtLee - 4 years ago 138
Java Question

Java regular expression capture group of numbers

I'm having a heck of a time getting this regular expression to output the groups I expect:

Pattern p = Pattern.compile("(point) (.*)");
Matcher m = p.matcher("point 0 0 255 0 0");

if (m.find()) {
for (int i = 0; i < m.groupCount(); i++) {
System.out.println("-- " + m.group(i));
}
}


I am hoping to see this output:

point 0 0 255 0 0 // this is group 0
point
0 0 255 0 0


Instead, I get group
0
and
1
- nothing from the last group.

I don't know what I'm doing wrong.

In the long run, I'm trying to match
(point|rect|line)
and a variable number of integers.

Thanks...

Answer Source

You are not printing all the groups. Try for (int i = 0; i <= m.groupCount(); i++)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download