Python regex match OR operator

后端 未结 5 882
轮回少年
轮回少年 2021-02-07 13:11

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


        
5条回答
  •  没有蜡笔的小新
    2021-02-07 13:42

    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

提交回复
热议问题