且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-10-16 22:15:02

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

Use a non capturing group (?: and reference to the match group.

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

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

您也可以使用 re.findall() 进行递归匹配.

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)

参见演示