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?
match() re. match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With