+ 2
Regex not working...
import re pattern = r"^\d{2}[\.-]\d{2}[\.-]\d{4}\s \d{2}[\.:]\d{2}[\.:]\d{2}" match = re.match(pattern, "01-01-1977 12:56:33") if match: print("Match 1") match = re.match(pattern, "2-29-2012 3:30:33") if match: print("Match 2") match = re.match(pattern, " ! $?") if match: print("Match 3")
3 Answers
+ 3
I see what it is. Your pattern is what's wrong...
"\s \d"
That portion is the culprit. \s allows 1 tab, space,new line etc but in your string you added spaces of your own. So it's looking for a newline/tab/space followed by another 4 spaces. Remember spaces in your Regex String counts too.
How to fix this?
pattern = r"^\d{2}[\.-]\d{2}[\.-]\d{4}\s\d{2}[\.:]\d{2}[\.:]\d{2}"
# I swear typing Regex is a pain in the arse.
# :^)
+ 2
Hi Dennis,
depending on how strict you wish to be, you could also use match.search instead of match.match and using groups to the portions you desire and using ".*?" in between, what could be one or more different characters.
pattern = re.compile('(\d{1,2}[\.-]\d{1,2}[\.-]\d{4}).*?(\d{1,2}[\.:]\d{1,2}[\.:]\d{1,2})')
match = pattern.search("2-29-2012 3:30:33")
date = match.group(1)
time = match.group(2)
I changed the code a little bit, to work with 1 or 2 digits in the dates and times.
hope this helps.
+ 1
Thanks Don! extra 4 spaces threw me off;)