Python正则表达式匹配OR运算符

Mar*_*edy 12 python regex string time

我正在尝试在AM或PM中匹配时间格式.

i.e. 02:40PM
     12:29AM 
Run Code Online (Sandbox Code Playgroud)

我正在使用以下正则表达式

timePattern = re.compile('\d{2}:\d{2}(AM|PM)')
Run Code Online (Sandbox Code Playgroud)

但它只返回AM PM没有数字的字符串.出了什么问题?

hwn*_*wnd 24

使用非捕获组(?:并引用匹配组.

使用re.I不区分大小写的匹配.

import re

def find_t(text):
    return re.search(r'\d{2}:\d{2}(?:am|pm)', text, re.I).group()
Run Code Online (Sandbox Code Playgroud)

您还可以使用re.findall()递归匹配.

def find_t(text):
    return re.findall(r'\d{2}:\d{2}(?:am|pm)', text, re.I)
Run Code Online (Sandbox Code Playgroud)

看到 demo


小智 7

使用非分隔的捕获组(?:...)

>>> from re import findall
>>> mystr = """
... 02:40PM
... 12:29AM
... """
>>> findall("\d{2}:\d{2}(?:AM|PM)", mystr)
['02:40PM', '12:29AM']
>>>
Run Code Online (Sandbox Code Playgroud)

此外,您可以将 Regex 缩短为\d\d:\d\d(?:A|P)M.