Python正则表达式匹配OR运算符 [英] Python regex match OR operator
本文介绍了Python正则表达式匹配OR运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试匹配上午或下午的时间格式.
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)')
但它一直只返回 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.
使用 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)
参见演示
这篇关于Python正则表达式匹配OR运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文