How do you match 12 hour time hh:mm in a regex?

前端 未结 11 944
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-03 01:48

How could you match 12 hour time in a regex-- in other words match 12:30 but not 14:74? Thanks!

相关标签:
11条回答
  • 2021-01-03 02:23

    why regex? you can do this will simple integer check

    $str = "12:74";
    list($h , $m ) = explode(":",$str);
    if ( ($h <=12 && $h >=0  ) && ($m <=59 && $m >=0) ) {
        print "Time Ok.";
    }else{
        print "Time not ok";
    }
    
    0 讨论(0)
  • 2021-01-03 02:25

    The following matches padded and non-padded hours in a 24hr clock (i.e. 00:00 - 23:59) between 00:00 and 12:59.

    (?:(?<!\d)[0-9]|0[0-9]|1[0-2]):[0-5][0-9]
    

    Matches:

    • 00:00
    • 00:58
    • 01:34
    • 1:34
    • 8:35
    • 12:23
    • 12:59

    Nonmatches:

    • 13:00
    • 13:23
    • 14:45
    • 23:59
    0 讨论(0)
  • 2021-01-03 02:27
    ^(00|0[0-9]|1[012]):[0-5][0-9] ?((a|p)m|(A|P)M)$
    

    ^ - Match the beginning of the string.

    (00|0[0-9]|1[012]) - any two-digit number up to 12. Require two digits.

    : - Match a colon

    [0-5][0-9] - Match any two-digit number from 00 to 59.

    ? - Match a space zero or one times.

    ((a|p)m|(A|P)M) - Match am or pm, case insensitive.

    $ - Match the end of the string.

    0 讨论(0)
  • 2021-01-03 02:27

    You could use this one:

    /((?:1[0-2])|(?:0?[0-9])):([0-5][0-9]) ?([ap]m)/
    
    /1 => hour
    /2 => minute
    /3 => am/pm
    
    0 讨论(0)
  • 2021-01-03 02:33
    (0?\d|1[0-2]):([0-5]\d)
    

    That will match everything from 0:00 up to 12:59. That's 13 hours, by the way. If you don't want to match 0:00 - 0:59, try this instead:

    ([1-9]|1[0-2]):([0-5]\d)
    
    0 讨论(0)
  • 2021-01-03 02:36

    I believe the above fail in at least one way, particularly regarding strings such as "13:00" (Keith's matches "3:00" in that case).

    This one should handle that issue as well as the others brought up.

    ([01][0-2]|(?<!1)[0-9]):([0-5][0-9])
    
    0 讨论(0)
提交回复
热议问题