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

You can use this regular expression:

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

If you want to exclude 00:00, you can use this expression

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

Second expression is better option because valid time is 00:01 to 00:59 or 0:01 to 23:59. You can use any of these upon your requirement. Regex101 link

查看更多
唯独是你
3楼-- · 2019-01-02 15:55

You can use this one 24H, seconds are optional

^([0-1]?[0-9]|[2][0-3]):([0-5][0-9])(:[0-5][0-9])?$
查看更多
余欢
4楼-- · 2019-01-02 15:56

Mine is:

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

This is much shorter

Got it tested with several example

Match:

  • 00:00
  • 7:43
  • 07:43
  • 19:00
  • 18:23

And doesn't match any invalid instance such as 25:76 etc ...

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

You can use following regex :

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

Only modification I have made is leftmost digit is optional. Rest of the regex is same.

查看更多
妖精总统
6楼-- · 2019-01-02 15:58

Amazingly I found actually all of these don't quite cover it, as they don't work for shorter format midnight of 0:0 and a few don't work for 00:00 either, I used and tested the following:

^([0-9]|0[0-9]|1?[0-9]|2[0-3]):[0-5]?[0-9]$
查看更多
素衣白纱
7楼-- · 2019-01-02 15:58

Declare

private static final String TIME24HOURS_PATTERN = "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]";

public boolean validate(final String time) {
    pattern = Pattern.compile(TIME24HOURS_PATTERN);
    matcher = pattern.matcher(time);
    return matcher.matches();
}

This method return "true" when String match with the Regular Expression.

查看更多
登录 后发表回答