Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to find a specific pattern in python [closed]

Tags:

python

regex

I am using Python 2.7 and I have a great chunk of string data. I need to parse out a specific pattern from it. The pattern is as follows:

November 5 - December 10
Another example:
September 23 - December 16 

I want to use a regex to find data in this pattern. That is a string of characters, followed by a space, followed by a number, followed by a ' - ' , and then a string of characters again and then space followed by a number!

I know it sounds complicated but can someone please help me!

like image 828
Hamza Tahir Avatar asked Dec 13 '25 18:12

Hamza Tahir


1 Answers

You can just do this in a pretty straightforward way:

import re

text = """
November 5 - December 10
September 23 - December 16
"""

matches = re.findall("\w+\s\d+\s\-\s\w+\s\d+", text)
print matches

prints:

['November 5 - December 10', 'September 23 - December 16']

But, if these words are just month names, you can improve your regexp by specifying a list of months instead of just \w+:

months = "|".join(calendar.month_name)[1:]
matches = re.findall("{0}\s\d+\s\-\s{0}\s\d+".format(months), text)
like image 121
alecxe Avatar answered Dec 15 '25 08:12

alecxe