I'm trying to match time formats in AM or PM.
i.e. 02:40PM
12:29AM
I'm using the following regex
timePattern = re.compile('\d{2}:\d{2}(AM|PM)')
but it keeps returning only AM PM string without the numbers. What's going wrong?
Use a non capturing group (?: and reference to the match group.
Use re.I for case insensitive matching.
import re
def find_t(text):
return re.search(r'\d{2}:\d{2}(?:am|pm)', text, re.I).group()
You can also use re.findall() for recursive matching.
def find_t(text):
return re.findall(r'\d{2}:\d{2}(?:am|pm)', text, re.I)
See demo
It sounds like you're accessing group 1, when you need to be accessing group 0.
The groups in your regex are as follows:
\d{2}:\d{2}(AM|PM)
|-----| - group 1
|----------------| - group 0 (always the match of the entire pattern)
You can access the entire match via:
timePattern.match('02:40PM').group(0)
findall()returns only those, not the full match.(AM|PM)to[AP]M.