I’m trying to get the following regex to work on my String:
Pattern Regex = Pattern.compile("(?:(\\d+) ?(days?|d) *?)?(?:(\\d+) ?(hours?|h) *?)?(?:(\\d+) ?(minutes?|m) *?)?(?:(\\d+) ?(seconds?|s))?",
Pattern.CANON_EQ | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher RegexMatcher = Regex.matcher(myString);
while (RegexMatcher.find()) {
...
}
.. it basically splits a string like 1day 3 hours into matched regex groups.
The problem I’m having is that when I get into the while loop, calls to RegexMatcher.group(i) will always return a NULL value, meaning they were not found in the string.
When I try to output RegexMatcher.group(0), it returns an empty string, even though myString definitelly contains like "hello 1d" – which should return at least 1st group as "1" and second as "d".
I’ve checked and double-checked the regex and it seems to be ok. No Idea what’s wrong here.
Thanks for any ideas 🙂
For a matcher
m, input sequences, and group indexg, the expressionsm.group(g)ands.substring(m.start(g), m.end(g))are equivalent.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 tom.group().If the match was successful but the group specified failed to match any part of the input sequence, then
nullis returned. Note that some groups, for example(a*), match the empty string. This method will return the empty string when such a group successfully matches the empty string in the input.If you want to ergodic all the matches, you can code like :
Note:
m.group()is equivalent tom.group(0)