I have date strings of the following forms
‘8 april 2022’, ‘8 april’, ‘april’
and a regex to try and match any of them
re.findall(r"(\d{1,2})?.*(januari|februari|maart|april|mei|juni|juli|augustus|september|oktober|november|december).*(202\d)?", str)
the problem is it will return ('8', 'april', '') in case of str = '8 april 2022'
so my question is why does ? ignore 1 occurrence of 202\d when its there?
Thank you.
EDIT. with non greedy .*?
re.findall(r"(\d{1,2}).*?(januari|februari|maart|april|mei|juni|juli|augustus|september|oktober|november|december).*?(202\d)?", str)
its still doesnt capture 2022
EDIT 2. Considering the answers a better question would be:
Is there a way of saying ‘hey regex 1 occurrence is optional but preferable to 0’ ?
>Solution :
.* should be rarely used due to the greediness .* after matching month is matching too much and not leaving anything to match in 3rd capture group for year. Also you just need to match 1+ spaces between strings.
You may use this regex with non-optional matches, word boundary and bit of tweaking:
\b(?:(\d{1,2}) +)?(januari|februari|maart|april|mei|juni|juli|augustus|september|oktober|november|december)(?: +(202\d))?