Regular expression syntax for hours

帅比萌擦擦* 提交于 2020-06-17 05:17:41

问题


I need a regular expression for hours in PHP, I am using ereg. I need it to accept 1-23 without leading zeros.

^([1-9])|([1][0-9])|([2][0-3])$

That's what I am using but I cannot find where is the mistake.


回答1:


Alternations (|) apply to everything in the surrounding group or globally if not in a group. So in your pattern, the ^ only applies to the first pattern and the $ only applies to the last pattern. In other words, your pattern matches any string which begins with a digit from 1 to 9, contains a 1 followed by a digit from 0 to 9, or ends with a 2 followed by a digit from 0 to 3.

Try putting the different options in one group:

^([1-9]|1[0-9]|2[0-3])$

Also note, 24-hour time starts at 00:00, so your pattern should look more like this:

^(1?[0-9]|2[0-3])$

Or this, if you need the hour to be 2 digits:

^([01][0-9]|2[0-3])$


来源:https://stackoverflow.com/questions/22256002/regular-expression-syntax-for-hours

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