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

前端 未结 11 992
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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.

提交回复
热议问题