Wednesday, 18 September 2013

Java Regexp does not match exact number of matches

Java Regexp does not match exact number of matches

I've got the following string:
0 days 00 hour 20 min 51 sec
I would like to extract all the numbers from it using Java's Regular
Expressions:
Pattern pattern = Pattern.compile("(\\d){1,2} days (\\d){2} hour (\\d){2}
min (\\d){2} sec");
Matcher m = pattern.matcher("0 days 00 hour 20 min 51 sec");
To my surprisde m.group(4) returns 1 and not 51. The same goes for
m.group(2) which returns 0 and not 00
I found this confusing since {n} should match exactly n occurrences of the
preceding expression , not ?

No comments:

Post a Comment