HH:MM:SS 时间字符串的正则表达式模式
我想解析一个 hh:mm:ss
字符串。 一个简单的就是 ([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)
它需要 2:3:24
或 02:03:24
字符串。
我想更进一步,通过验证,即使
- ,则 56 可以被视为 56 秒 [SS]
- 您只输入 56,也应该通过,因为如果您输入 2:3 或 02:03 或 02 :3 或 2:03 应该会过去。 2 分 3 秒 [MM:SS]
- 如果输入 20:30:12 则通过 20 小时 30 分 12 秒 [HH:MM:SS]
- 如果输入 78:12 则不通过 78 分钟是错误的。 ...
基本上,如果找到一个“:”,则将“:”之前的数字视为MM,将“:”之后的数字视为SS 。如果发现两个“:”,请考虑为 HH:MM:SS
我想出了这种模式。
(^([0-1]?\d|2[0-3]):([0-5]?\d):([0-5]?\d)$)|(^([0-5]?\d):([0-5]?\d)$)|(^[0-5]?\d$)
看起来运行良好。我想知道任何其他更简单的正则表达式,可以完成这项工作。
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
- 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....
Basically, if one ":" is found, consider number before ":" as MM and number after ":" as SS
. If two ":" are found consider as HH:MM:SS
I came up with this pattern.
(^([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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
说明:
Explanation:
@Tim Pietzcker 涵盖了 OP 对 HH:MM:SS 解析器的要求,其中 SS 是强制性的,即
如果您允许我稍微偏离 OP 的要求,并考虑 HH 的情况是强制性的,即
我想出的正则表达式是:
让我们分解它:
([0-1]?\d|2[0-3])
- 匹配小时(?::([0-5]?\d))?
- 可选择匹配分钟(?::([0-5]?\d))?
- 可选择匹配秒@Tim Pietzcker covers the OP's requirement for a HH:MM:SS parser where SS was mandatory, i.e.
If you permit me to deviate from the OP's requirement for a bit, and consider a case where HH is mandatory, i.e.
The regex I came up with was:
Let's break it down:
([0-1]?\d|2[0-3])
- matches for hours(?::([0-5]?\d))?
- optionally matches for minutes(?::([0-5]?\d))?
- optionally matches for seconds