Reputation: 18288
/^\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.
Upvotes: 15
Views: 45957
Reputation: 1
^(([0-9]{1})|([0-1]{1}[0-9]{1})|([2]{1}[0-3]{1}))(([:]{1})?)(([0-5]{1}[0-9]?)?)$
^(([0-9]{1})|([0-1]{1}[0-9]{1})|([2]{1}[0-3]{1}))([:]{1})([0-5]{1}[0-9]{1})$
Upvotes: 0
Reputation: 6112
For folks looking for 24h format matching,
hh:mm:ss or h:mm:ss :
status = /^(2[0-3]|[0-1]?[\d]):[0-5][\d]:[0-5][\d]$/.test(timestr)
hh:mm or h:mm :
status = /^(2[0-3]|[0-1]?[\d]):[0-5][\d]$/.test(timestr)
This site is great for testing out: https://www.regexpal.com/
Addedum: Explanation for completeness:
^
: start of string, $
: end of string. So we put the expression in a ^..$
block to ensure there's nothing outside of our pattern.(2[0-3]|[0-1]?[\d])
: translates to 2[0-3]
OR [0-1]?[\d]
2[0-3]
: 20, 21, 22, 23[0-1]?[\d]
: 0 or 1 or nothing (?
) followed by any single digit(\d
). So, this works for numbers from 0 to 19.:
just that character[0-5][\d]
: number from 00 to 59. Note: this won't tolerate single-digit in the mm place.Upvotes: 10
Reputation: 721
This is perfect: ^0?([0-9][0-2]?):[0-5][0-9]$
Note: 12 Hr Clock Only
For Times like: 0:01- 12:59
or
00:01 - 12:59
Upvotes: 0
Reputation: 21
Thanks!!! I use this Javascript code now:
function Check_arrival(time) {
//Assuming you are working in 12 hour time, 0 is not a valid
var patt = new RegExp("^(0?[1-9]|1[012]):[0-5][0-9]$");
var res = patt.test(time);
return res;
}
res=true|false
Upvotes: 2
Reputation: 11814
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]$/
Upvotes: 22
Reputation: 2009
/^(10|11|12|[1-9]):[0-5][0-9]$/
I don't think that you want 0:50 as a valid time either.
Upvotes: 7
Reputation: 523304
The 0 - 9 and 10 - 12 cases need to be treated separately. (The two rules can be combined with |
.)
/^(?:0?\d|1[012]):[0-5]\d$/
Here
(?:…)
is a non-capturing groupx|y
means match either pattern0?\d
matches 0 - 9 or 00 - 091[012]
matches 10 - 12.Upvotes: 12