Regular expression for matching HH:MM time format

2019-01-02 14:59发布

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]$

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

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.

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

标签: regex
18条回答
浅入江南
2楼-- · 2019-01-02 15:35

You can try the following

^\d{1,2}([:.]?\d{1,2})?([ ]?[a|p]m)?$

It can detect the following patterns :

2300 
23:00 
4 am 
4am 
4pm 
4 pm
04:30pm 
04:30 pm 
4:30pm 
4:30 pm
04.30pm
04.30 pm
4.30pm
4.30 pm
23:59 
0000 
00:00
查看更多
笑指拈花
3楼-- · 2019-01-02 15:36

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

This may work better:

^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
查看更多
高级女魔头
4楼-- · 2019-01-02 15:39

The best would be for HH:MM without taking any risk.

^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$
查看更多
路过你的时光
5楼-- · 2019-01-02 15:40

A slight modification to Manish M Demblani's contribution above handles 4am (I got rid of the seconds section as I don't need it in my application)

^(([0-1]{0,1}[0-9]( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[1-9]|1[0-2])(:|\.)[0-5][0-9]( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5][0-9]))$

handles: 4am 4 am 4:00 4:00am 4:00 pm 4.30 am etc..

查看更多
浪荡孟婆
6楼-- · 2019-01-02 15:44

As you asked the left most bit optional, I have done left most and right most bit optional too, check it out

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

It matches with

0:0 
00:00
00:0 
0:00
23:59
01:00
00:59

The live link is available here

查看更多
何处买醉
7楼-- · 2019-01-02 15:44

The below regex will help to validate hh:mm format

^([0-1][0-9]|2[0-3]):[0-5][0-9]$
查看更多
登录 后发表回答