Naik
Naik

Reputation: 1255

Regular expression in python finding dates

I am using regular expressions in python to finds dates like 09/2010 or 8/1976 but not 11/12/2010. I am using the following lines of codes but it does not work in some cases.

r'([^/](0?[1-9]|1[012])/(\d{4}))'

Upvotes: 1

Views: 76

Answers (3)

Naik
Naik

Reputation: 1255

After working on this problem I came to this solution:

This works very well!

df['text'].str.extractall(r'(?P<Date>(?P<month>\d{1,2})/?(?P<day>\d{1,2})?/(?P<year>\d{2,4}))')

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195438

This, a little bit explicit code, uses re.sub and datetime.strptime to parse/validate the input string:

import re
import datetime

s = '09/2010, 8/1976, 11/8/2010, 09/06/15, 12/1987, 13/2011, 09/13/2001'

r = re.compile(r'\b(\d{1,2})/(?:(\d{1,2})/)?(\d{2,4})\b')

def validate_date(g, parsed_values):
    if not g.group(2) is None:
        s = '{:02d}/{:02d}/{:04d}'.format(*map(int, g.groups()))
    else:
        s = '01/{:02d}/{:04d}'.format(int(g.group(1)), int(g.group(3)))

    try:
        datetime.datetime.strptime(s, '%d/%m/%Y')
        parsed_values.append(g.group())
        return
    except:
        pass

parsed_values = []
r.sub(lambda g: validate_date(g, parsed_values), s)

print(parsed_values)

Prints:

['09/2010', '8/1976', '11/8/2010', '09/06/15', '12/1987']

EDIT: Shortened the code.

Upvotes: 1

palvarez
palvarez

Reputation: 1598

import re

rgx = "(?:\d{1,2}\/)?\d{1,2}\/\d{2}(?:\d{2})?"
dates = "09/2010, 8/1976, 11/12/2010, 09/06/15 .."

result = re.findall(rgx, dates)
print(result)
# ['09/2010', '8/1976', '11/12/2010', '09/06/15']

Upvotes: 1

Related Questions