I'm doing an exercise in Python, and I'm stuck at this part where I have to detect dates in a string using re.
My only problem is that I when the day is "1st", it outputs a blank string. What am I doing wrong?
import re
text = "article 1st May 1988; another article 2 June 1992, some new article 25 October 2001; "
result = re.findall(r'(\d*) ([A-Z]\w+) (\d+)',text)
print(result)
Output
[('', 'May', '1988'), ('2', 'June', '1992'), ('25', 'October', '2001')]
Thanks for the help
You could force at least one number (with \d+ instead of just \d*) and add a subset of possible strings for ordinals :
import re
text = "article 1st May 1988; another article 2 June 1992, some new article 25 October 2001; "
result = re.findall(r'(\d+(?:st|nd|rd|th)?) ([A-Z]\w+) (\d+)',text)
print(result)
# [('1st', 'May', '1988'), ('2', 'June', '1992'), ('25', 'October', '2001')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With