Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python regex doesnt match 1 occurrence with 0 or 1 occurrences operator?

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 .*?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))?

RegEx Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading