Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx - Time Validation ((h)h:mm)

/^\d{1,2}[:][0-5][0-9]$/

is what I have. this limits minutes to 00-59. It does not, however, limit hours to between 0 and 12. For similarity and uniformity I would like to do this with RegEx alone if possible.

Further-more I would like the first digit to be optional. i.e. 09:30 accepted as well as 9:30. I played around with ranges, but something out of range is always acceptable.

like image 921
Joshua Enfield Avatar asked Apr 28 '10 20:04

Joshua Enfield


People also ask

How does regular expression validate time in 24 hour format?

In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›. On a 24-hour clock, if the first digit is 0 or 1, the second digit allows all 10 digits, but if the first digit is 2, the second digit must be between 0 and 3. In regex syntax, this can be expressed as ‹ 2[0-3]|[01]?[0-9] ›.

How does regular expression validate time in 12-hour format?

On a 12-hour clock, if the first digit is 0, the second digit allows all 10 digits, but if the first digit is 1, the second digit must be 0, 1, or 2. In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›.

What is time complexity of regex?

Time Complexity of Regex is O(MxN).

Which regex pattern can be used to find the time?

regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]"; Where: ( represents the start of the group. [01]?[0-9] represents the time starts with 0-9, 1-9, 00-09, 10-19.


1 Answers

Assuming you are working in 12 hour time, 0 is not a valid hour and should also be excluded (as pointed out by Jon). Here is a basic solution:

/^(0?[1-9]|1[012]):[0-5][0-9]$/

A 24-hour time regex matcher that works similarly:

/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/
like image 99
Trey Hunner Avatar answered Sep 17 '22 18:09

Trey Hunner