Reputation: 5432
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
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 4You now have:
Upvotes: 4
Reputation: 1683
It should be (\\d{1,2})
You're leaving the repetition operator out of the group.
Upvotes: 0
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