Regex for only hours or hours and minutes

早过忘川 提交于 2021-02-04 20:42:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!