Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex match OR operator

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?

like image 601
Mark Kennedy Avatar asked Nov 06 '13 19:11

Mark Kennedy


People also ask

What is regex match in Python?

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.

How do you do a regex match?

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).

What does '$' mean in regex?

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.


1 Answers

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

like image 181
hwnd Avatar answered Oct 13 '22 22:10

hwnd