Regular expression for matching HH:MM time format

前端 未结 19 2433
甜味超标
甜味超标 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:44

    You can try the following

    ^\d{1,2}([:.]?\d{1,2})?([ ]?[a|p]m)?$
    

    It can detect the following patterns :

    2300 
    23:00 
    4 am 
    4am 
    4pm 
    4 pm
    04:30pm 
    04:30 pm 
    4:30pm 
    4:30 pm
    04.30pm
    04.30 pm
    4.30pm
    4.30 pm
    23:59 
    0000 
    00:00
    
    0 讨论(0)
  • 2020-11-22 17:44

    check this masterfull timestamp detector regex I built to look for a user-specified timestamp, examples of what it will pickup include, but is most definitely NOT limited to;

    8:30-9:40
    09:40-09 : 50
    09 : 40-09 : 50
    09:40 - 09 : 50
    08:00to05:00
    08 : 00to05 : 00
    08:00 to 05:00
    8am-09pm
    08h00 till 17h00
    8pm-5am
    08h00,21h00
    06pm untill 9am
    

    It'll also pickup many more, as long as the times include digits

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

    The best would be for HH:MM without taking any risk.

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

    Regular Expressions for Time

    • HH:MM 12-hour format, optional leading 0

        /^(0?[1-9]|1[0-2]):[0-5][0-9]$/
      
    • HH:MM 12-hour format, optional leading 0, mandatory meridiems (AM/PM)

        /((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/
      
    • HH:MM 24-hour with leading 0

       /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
      
    • HH:MM 24-hour format, optional leading 0

       /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
      
    • HH:MM:SS 24-hour format with leading 0

       /(?:[01]\d|2[0-3]):(?:[0-5]\d):(?:[0-5]\d)/
      

    Reference and Demo

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

    Matches:

    2:9
    2:09
    2:59
    02:9
    02:09
    02:59
    23:59
    

    Use it:

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

    Your original regular expression has flaws: it wouldn't match 04:00 for example.

    This may work better:

    ^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$
    
    0 讨论(0)
提交回复
热议问题