Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with string selection with re in python

Tags:

python

regex

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

like image 516
Vectrex28 Avatar asked Jul 14 '26 10:07

Vectrex28


1 Answers

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')]
like image 183
Eric Duminil Avatar answered Jul 22 '26 13:07

Eric Duminil