I want a regexp for matching time in HH:MM format. Here's what I have, and it works:
^[0-2][0-3]:[0-5][0-9]$
This matches everything from 00:00 to 23:59.
However, I want to change it so 0:00 and 1:00, etc are also matched as well as 00:00 and 01:30. I.e to make the leftmost digit optional, to match HH:MM as well as H:MM.
Any ideas how to make that change? I need this to work in javascript as well as php.
Try the following
Note: I was assuming the javascript regex engine. If it's different than that please let me know.
Regular Expressions for Time
HH:MM 12-hour format, optional leading 0
HH:MM 12-hour format, optional leading 0, mandatory meridiems (AM/PM)
HH:MM 24-hour with leading 0
HH:MM 24-hour format, optional leading 0
HH:MM:SS 24-hour format with leading 0
Reference and Demo
Matches:
Use it:
None of the above worked for me. In the end I used:
Logic:
The first number (hours) is either: a number between 0 and 19 -->
[0-1]?[0-9]
(allowing single digit number)or
a number between 20 - 23 -->
2[0-3]
the second number (minutes) is always a number between 00 and 59 -->
[0-5][0-9]
(not allowing a single digit)You can use following regex:
check this masterfull timestamp detector regex I built to look for a user-specified timestamp, examples of what it will pickup include, but is most definitely NOT limited to;
It'll also pickup many more, as long as the times include digits