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
You can use following regex :
^[0-2]?[0-3]:[0-5][0-9]$
Only modification I have made is leftmost digit is optional. Rest of the regex is same.
You can use this one 24H, seconds are optional
^([0-1]?[0-9]|[2][0-3]):([0-5][0-9])(:[0-5][0-9])?$
As you asked the left most bit optional, I have done left most and right most bit optional too, check it out
^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]?$
It matches with
0:0
00:00
00:0
0:00
23:59
01:00
00:59
The live link is available here
Declare
private static final String TIME24HOURS_PATTERN = "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]";
public boolean validate(final String time) {
pattern = Pattern.compile(TIME24HOURS_PATTERN);
matcher = pattern.matcher(time);
return matcher.matches();
}
This method return "true" when String match with the Regular Expression.
Mine is:
^(1?[0-9]|2[0-3]):[0-5][0-9]$
This is much shorter
Got it tested with several example
Match:
And doesn't match any invalid instance such as 25:76 etc ...
Amazingly I found actually all of these don't quite cover it, as they don't work for shorter format midnight of 0:0 and a few don't work for 00:00 either, I used and tested the following:
^([0-9]|0[0-9]|1?[0-9]|2[0-3]):[0-5]?[0-9]$