问题
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.
回答1:
^(([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.
回答2:
Just make the last part optional, like this:
^(([0-9])|([0-1][0-9])|([2][0-3]))(:(([0-9])|([0-5][0-9])))?$
来源:https://stackoverflow.com/questions/11225981/regex-for-only-hours-or-hours-and-minutes