HH:MM:SS时间字符串的正则表达式 [英] Regex pattern for HH:MM:SS time string
本文介绍了HH:MM:SS时间字符串的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想解析一个 hh:mm:ss
string。
一个简单的一个是([0-1]?\d | 2 [0-3]):([0-5]?\d):([0-5 ]?\d)
其中期望 2:3:24
或 02:03:24
字符串。
I want to parse a hh:mm:ss
string.
A simple one is ([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)
which expects 2:3:24
or 02:03:24
string.
我想进一步通过验证,即使在
I want to take it a step further and pass the validation even in cases like
- 或2:03它应该通过。 2分3秒[MM:SS]
- 如果您输入20:30:12通过20小时,30分钟和12秒[HH:MM:SS]
- 如果输入78:12,不通过78分钟是错误的....
如果您输入的只是56,则应通过,如果输入2:3或02:03或02:3,则56可被视为56秒[SS]
- if you enter just 56, it should be pass, as 56 can be considered as 56 secs [SS]
- if you enter 2:3 or 02:03 or 02:3 or 2:03 it should pass. 2 minutes and 3 seconds [MM:SS]
- If you enter 20:30:12 pass with 20 hrs, 30 minutes and 12 secs [HH:MM:SS]
- if you enter 78:12 , do not pass 78 minutes is wrong....
基本上,如果找到一个:,请将:之前的数字设为MM,将:后的数字设为SS
。如果发现两个:被认为是HH:MM:SS
Basically, if one ":" is found, consider number before ":" as MM and number after ":" as SS . If two ":" are found consider as HH:MM:SS
我想出了这种模式。
(^([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)$)|(^([0-5]?\d):([0-5]?\d)$)|(^[0-5]?\d$)
似乎工作正常。我想知道任何其他更简单的正则表达式,可以做这个工作。
It seems to be working fine. I wanted to know any other simpler regular expression, that can do the job.
推荐答案
^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)$
说明:
^ # Start of string
(?: # Try to match...
(?: # Try to match...
([01]?\d|2[0-3]): # HH:
)? # (optionally).
([0-5]?\d): # MM: (required)
)? # (entire group optional, so either HH:MM:, MM: or nothing)
([0-5]?\d) # SS (required)
$ # End of string
这篇关于HH:MM:SS时间字符串的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文