军事(24小时)格式的匹配时间的正则表达式 [英] Regular expression for matching time in military (24 hour) format

查看:65
本文介绍了军事(24小时)格式的匹配时间的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个JavaScript正则表达式,它可以使用24小时制来匹配时间,其中时间是带或不带冒号的.

I would like a JavaScript regular expression that will match time using the 24 hour clock, where the time is given with or without the colon.

例如,我想以以下格式匹配时间:

For example, I would like to match time in the following formats:

  • 0800
  • 23:45
  • 2345

但不匹配无效时间,例如

but that would not match invalid times such as

  • 34:68
  • 5672

推荐答案

这应该做到:

^([01]\d|2[0-3]):?([0-5]\d)$

表达式为:

^        Start of string (anchor)
(        begin capturing group
  [01]   a "0" or "1"
  \d     any digit
 |       or
  2[0-3] "2" followed by a character between 0 and 3 inclusive
)        end capturing group
:?       optional colon
(        start capturing
  [0-5]  character between 0 and 5
  \d     digit
)        end group
$        end of string anchor

这篇关于军事(24小时)格式的匹配时间的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆