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:46

Try the following

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

Note: I was assuming the javascript regex engine. If it's different than that please let me know.

查看更多
皆成旧梦
3楼-- · 2019-01-02 15:47

Regular Expressions for Time

  • HH:MM 12-hour format, optional leading 0

    /^(0?[1-9]|1[0-2]):[0-5][0-9]\d$/
    
  • HH:MM 12-hour format, optional leading 0, mandatory meridiems (AM/PM)

    /((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/
    
  • HH:MM 24-hour with leading 0

    /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
    
  • HH:MM 24-hour format, optional leading 0

    /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
    
  • HH:MM:SS 24-hour format with leading 0

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

Reference and Demo

查看更多
后来的你喜欢了谁
4楼-- · 2019-01-02 15:51

Matches:

2:9
2:09
2:59
02:9
02:09
02:59
23:59

Use it:

^([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9])$
查看更多
心情的温度
5楼-- · 2019-01-02 15:52

None of the above worked for me. In the end I used:

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

Logic:

The first number (hours) is either: a number between 0 and 19 --> [0-1]?[0-9] (allowing single digit number)
or
a number between 20 - 23 --> 2[0-3]

the second number (minutes) is always a number between 00 and 59 --> [0-5][0-9] (not allowing a single digit)

查看更多
初与友歌
6楼-- · 2019-01-02 15:52

You can use following regex:

^[0-1][0-9]:[0-5][0-9]$|^[2][0-3]:[0-5][0-9]$|^[2][3]:[0][0]$
查看更多
浅入江南
7楼-- · 2019-01-02 15:53

check this masterfull timestamp detector regex I built to look for a user-specified timestamp, examples of what it will pickup include, but is most definitely NOT limited to;

8:30-9:40
09:40-09 : 50
09 : 40-09 : 50
09:40 - 09 : 50
08:00to05:00
08 : 00to05 : 00
08:00 to 05:00
8am-09pm
08h00 till 17h00
8pm-5am
08h00,21h00
06pm untill 9am

It'll also pickup many more, as long as the times include digits

查看更多
登录 后发表回答