Python regex match OR operator

后端 未结 5 821
轮回少年
轮回少年 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:51

    Use a non-delimited capture group (?:...):

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

    Also, you can shorten your Regex to \d\d:\d\d(?:A|P)M.

提交回复
热议问题