/^\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.
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] ›.
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] ›.
Time Complexity of Regex is O(MxN).
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.
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]$/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With