Regular expression for matching HH:MM time format

前端 未结 19 2395
甜味超标
甜味超标 2020-11-22 17:25

I want a regexp for matching time in HH:MM format. Here\'s what I have, and it works:

^[0-2][0-3]:[0-5][0-9]$

This matches everything from

相关标签:
19条回答
  • 2020-11-22 18:11

    Your code will not work properly as it will not work for 01:00 type formats. You can modify it as follows.

    pattern =r"^(0?[1-9]|1[0-2]):[0-5][0-9]$"
    

    Making it less complicated we can use a variable to define our hours limits.Further we can add meridiems for more accurate results.

    hours_limit = 12 
    pattern = r"^[1-hours_limit]:[0-5][0-9]\s?[AaPp][Mm]$"
    print(re.search(pattern, "2:59 pm"))
    
    0 讨论(0)
提交回复
热议问题