匹配 HH:MM 时间格式的正则表达式 [英] Regular expression for matching HH:MM time format

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

问题描述

我想要一个正则表达式来匹配 HH:MM 格式的时间.这是我所拥有的,并且有效:

I want a regexp for matching time in HH:MM format. Here's what I have, and it works:

^[0-2][0-3]:[0-5][0-9]$

这匹配从 00:00 到 23:59 的所有内容.

This matches everything from 00:00 to 23:59.

但是,我想更改它以便 0:00 和 1:00 等也匹配以及 00:00 和 01:30.即使最左边的数字可选,以匹配 HH:MM 和 H:MM.

However, I want to change it so 0:00 and 1:00, etc are also matched as well as 00:00 and 01:30. I.e to make the leftmost digit optional, to match HH:MM as well as H:MM.

有什么想法可以做出改变吗?我需要它在 javascript 和 php 中工作.

Any ideas how to make that change? I need this to work in javascript as well as php.

推荐答案

您原来的正则表达式有缺陷:例如,它与 04:00 不匹配.

Your original regular expression has flaws: it wouldn't match 04:00 for example.

这可能会更好:

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

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

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