Jonas Geiregat
Jonas Geiregat

Reputation: 5432

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 surprise 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, or not ?

Upvotes: 1

Views: 226

Answers (3)

rid
rid

Reputation: 63502

You likely wanted to catch both digits in the same group:

"(\\d{1,2}) days (\\d{2}) hour (\\d{2}) min (\\d{2}) sec"

This is what the original expression would do.

0 days 00 hour 20 min 51 sec
  • (\d){1,2} matches 0, places it in group 1
  • (\d){2} matches 0, places it in group 2, matches 0 again, places it in group 2
  • (\d){2} matches 2, places it in group 3, matches 0, places it in group 3
  • (\d){2} matches 5, places it in group 4, matches 1, places it in group 4

You now have:

  • 0 in group 1
  • 0 in group 2
  • 0 in group 3
  • 1 in group 4

Upvotes: 4

Yasen
Yasen

Reputation: 1683

It should be (\\d{1,2}) You're leaving the repetition operator out of the group.

Upvotes: 0

rolfl
rolfl

Reputation: 17707

The {...} structures should be inside the (...) parenthesis, e.g.

Pattern.compile("(\\d{1,2}) days (\\d{2}) hour (\\d{2}) min (\\d{2}) sec");

Upvotes: 3

Related Questions