Trying to write a RE to recognize date format mm/dd in Python
reg = "(((1[0-2])|(0?[1-9]))/((1[0-9])|(2[0-9])|(3[0-1])|(0?[0-9])))"
match = re.findall(reg, text, re.IGNORECASE)
print match
For text = ‘4/13’ it gives me
[('4/13', '4', '', '4', '13', '13', '', '', '')]
Just need the first element. I don’t want inexact matches, how do I remove them.
Thanks,
Cheng
You’re getting all those matches because each set of parentheses in your regular expression generates a match group. You can use a non-grouping match, such as
(?:...), if you really don’t want the groups in your result set. You can also simply take the first item from the list and ignore the others.This would make your expression look like:
See the
redocumentation for more information.Here’s a complete example: