>>> a = re.search('(\\d+h)?(\\d+m)?(\\d+s)?', 'in 1h15m')
>>> a.groups()
(None, None, None)
>>> a = re.search('.*(\\d+h)?(\\d+m)?(\\d+s)?', 'in 1h15m')
>>> a.groups()
(None, None, None)
>>> a = re.search('...(\\d+h)?(\\d+m)?(\\d+s)?', 'in 1h15m')
>>> a.groups()
('1h', '15m', None)
Why is the ‘…’ version the only one that populates ‘groups’?
Why are we getting empty groups?
First one –
a?a?amatched with"bbbaaa":a, but can’t find. That’s Ok, it’s optional, so match nothing. (x 3 times)Second one –
.*a?a?amatched with"bbbaaa":.*from the first position to the last position.a, but can’t find it. That’s Ok, it’s optional, so match nothing. (x 3 times)How to solve this issue?
It is unclear what exactly you are trying to do, but you can match for:
This assures you match at least one element – at least on option is not optional. Then, the regex would fail to match if none of the groups is available. You can parse it in a second step to get the groups, or use the group alternation feature
(?| | )if it is supported.