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

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

    This is an example of a problem where "hey I know, I'll use regular expressions!" is the wrong solution. You can use a regular expression to check that your input format is digit-digit-colon-digit-digit, then use programming logic to ensure that the values are within the range you expect. For example:

    /(\d\d?):(\d\d)/
    
    if ($1 >= 1 && $1 <= 12 && $2 < 60) {
        // result is valid 12-hour time
    }
    

    This is much easier to read and understand than some of the obfuscated regex examples you see in other answers here.

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

    Here is a 12 hour pattern with AM and PM validation.

    TIME12HOURSAMPM_PATTERN = "^(?:(?<!\\d)[0-9]|0[0-9]|1[0-2]):[0-5][0-9] ?((a|p)m|(A|P)M)$";

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

    This should work:

    ([1-9]|1[012]):[0-5][0-9]
    
    0 讨论(0)
  • 2021-01-03 02:49

    Like this: ((?:1[0-2]|0\d)\:(?:[0-5]\d)) if you want leading 0 for the hour, ((?:1[0-2]|\d)\:(?:[0-5]\d)) if you don't and ((?:1[0-2]|0?\d)\:(?:[0-5]\d)) if you don't care.

    0 讨论(0)
  • 2021-01-03 02:50
    ^(?:(?:1?(?:[0-2]))|[1-9]):[0-5][0-9]
    
    0 讨论(0)
提交回复
热议问题