Reputation: 2922
I am using regex ^(([0-9])|([0-1][0-9])|([2][0-3])):(([0-9])|([0-5][0-9]))$
for time. It is very good regex but when user wants to enter only hours like 8 or 12 without colon and minutes it is not allowing.
Can any one suggests which regular expressions suits hours only or hours:minutes.
Upvotes: 2
Views: 4789
Reputation: 39283
^(([0-9])|([0-1][0-9])|([2][0-3]))(:(([0-9])|([0-5][0-9])))?$
made the ":mm" part optional by putting it in ()
and adding a ?
quantifier.
An explanation as generated by https://www.regexplained.co.uk/
First group (labeled as "group #4"):
Then an optional second group (labeled as "group #8")
Upvotes: 4
Reputation: 46219
Just make the last part optional, like this:
^(([0-9])|([0-1][0-9])|([2][0-3]))(:(([0-9])|([0-5][0-9])))?$
Upvotes: 1