How could you match 12 hour time in a regex-- in other words match 12:30 but not 14:74? Thanks!
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.
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)$";
This should work:
([1-9]|1[012]):[0-5][0-9]
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.
^(?:(?:1?(?:[0-2]))|[1-9]):[0-5][0-9]