spicyramen spicyramen - 1 year ago 115
Python Question

Regex simplification using python re

Have the following date string which I need to match:

release_date1 = 'July 29, 2016'
release_date2 = 'August 2016'

res = re.match(r'(\w+)\s(\d+),\s(\d+)$', release_date1)
if res:
datestr = res.group(1) + '-' + res.group(2) + '-' + res.group(3)

res = re.match(r'(\w+)\s(\d+)$', release_date2)
if res:
datestr = res.group(1) + '-01-' + res.group(2)

Currently I have 2 separate regex, I'm looking to simplify my two regex expressions into a single one. Any suggestions?

Answer Source

Dirty solution but will match both:


You might also consider using or operator | which will give a little bit more precise result:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download