Regular expression for matching HH:MM time format

前端 未结 19 2435
甜味超标
甜味超标 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 17:51

    You can use this regular expression:

    ^(2[0-3]|[01]?[0-9]):([1-5]{1}[0-9])$
    

    If you want to exclude 00:00, you can use this expression

    ^(2[0-3]|[01]?[0-9]):(0[1-9]{1}|[1-5]{1}[0-9])$
    

    Second expression is better option because valid time is 00:01 to 00:59 or 0:01 to 23:59. You can use any of these upon your requirement. Regex101 link

    0 讨论(0)
  • 2020-11-22 17:53

    The below regex will help to validate hh:mm format

    ^([0-1][0-9]|2[0-3]):[0-5][0-9]$
    
    0 讨论(0)
  • 2020-11-22 17:55

    Try the following

    ^([0-2][0-3]:[0-5][0-9])|(0?[0-9]:[0-5][0-9])$
    

    Note: I was assuming the javascript regex engine. If it's different than that please let me know.

    0 讨论(0)
  • 2020-11-22 17:56

    A slight modification to Manish M Demblani's contribution above handles 4am (I got rid of the seconds section as I don't need it in my application)

    ^(([0-1]{0,1}[0-9]( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[1-9]|1[0-2])(:|\.)[0-5][0-9]( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5][0-9]))$
    

    handles: 4am 4 am 4:00 4:00am 4:00 pm 4.30 am etc..

    0 讨论(0)
  • 2020-11-22 17:59

    You can use following regex:

    ^[0-1][0-9]:[0-5][0-9]$|^[2][0-3]:[0-5][0-9]$|^[2][3]:[0][0]$
    
    0 讨论(0)
  • 2020-11-22 18:03

    None of the above worked for me. In the end I used:

    ^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$ (js engine)
    

    Logic:

    The first number (hours) is either: a number between 0 and 19 --> [0-1]?[0-9] (allowing single digit number)
    or
    a number between 20 - 23 --> 2[0-3]

    the second number (minutes) is always a number between 00 and 59 --> [0-5][0-9] (not allowing a single digit)

    0 讨论(0)
提交回复
热议问题