Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python and Regex to extract different formats of dates

Tags:

python

regex

I have the following code to match the dates

import re
date_reg_exp2 = re.compile(r'\d{2}([-/.])(\d{2}|[a-zA-Z]{3})\1(\d{4}|\d{2})|\w{3}\s\d{2}[,.]\s\d{4}')
matches_list = date_reg_exp2.findall("23-SEP-2015 and 23-09-2015 and 23-09-15 and Sep 23, 2015")
print matches_list

The output I expect is

["23-SEP-2015","23-09-2015","23-09-15","Sep 23, 2015"]

What I am getting is:

[('-', 'SEP', '2015'), ('-', '09', '2015'), ('-', '09', '15'), ('', '', '')]

Please check the link for regex here.

like image 315
Kartheek Palepu Avatar asked Dec 11 '15 10:12

Kartheek Palepu


2 Answers

The problem you have is that re.findall returns captured texts only excluding Group 0 (the whole match). Since you need the whole match (Group 0), you just need to use re.finditer and grab the group() value:

matches_list = [x.group() for x in date_reg_exp2.finditer("23-SEP-2015 and 23-09-2015 and 23-09-15 and Sep 23, 2015")]

See IDEONE demo

re.findall(pattern, string, flags=0)
Return all non-overlapping matches of pattern in string, as a list of strings... If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.

re.finditer(pattern, string, flags=0)
Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string.

like image 62
Wiktor Stribiżew Avatar answered Oct 19 '22 09:10

Wiktor Stribiżew


You could try this regex

date_reg_exp2 = re.compile(r'(\d{2}(/|-|\.)\w{3}(/|-|\.)\d{4})|([a-zA-Z]{3}\s\d{2}(,|-|\.|,)?\s\d{4})|(\d{2}(/|-|\.)\d{2}(/|-|\.)\d+)')

Then use re.finditer()

for m in re.finditer(date_reg_exp2,"23-SEP-2015 and 23-09-2015 and 23-09-15 and Sep 23, 2015"):
print m.group()

The Output will be

23-SEP-2015
23-09-2015
23-09-15
Sep 23, 2015

like image 2
Rohan Amrute Avatar answered Oct 19 '22 08:10

Rohan Amrute