Regular expression for matching HH:MM time format

前端 未结 19 2393
甜味超标
甜味超标 2020-11-22 17:25

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

相关标签:
19条回答
  • 2020-11-22 18:05

    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.

    0 讨论(0)
  • 2020-11-22 18:08

    You can use this one 24H, seconds are optional

    ^([0-1]?[0-9]|[2][0-3]):([0-5][0-9])(:[0-5][0-9])?$
    
    0 讨论(0)
  • 2020-11-22 18:08

    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

    0 讨论(0)
  • 2020-11-22 18:08

    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.

    0 讨论(0)
  • 2020-11-22 18:10

    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 ...

    0 讨论(0)
  • 2020-11-22 18:11

    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]$
    
    0 讨论(0)
提交回复
热议问题