Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 786
Adrian Sarli Avatar asked Jul 27 '09 20:07

Adrian Sarli


2 Answers

This should work:

([1-9]|1[012]):[0-5][0-9]
like image 133
Keith Avatar answered Oct 26 '22 22:10

Keith


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.

like image 30
Greg Hewgill Avatar answered Oct 26 '22 21:10

Greg Hewgill