Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for matching HH:MM time format

Tags:

regex

People also ask

How does regular expression validate time in 12 hour format?

On a 12-hour clock, if the first digit is 0, the second digit allows all 10 digits, but if the first digit is 1, the second digit must be 0, 1, or 2. In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›.

Which regex pattern can be used to find the time?

In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›. On a 24-hour clock, if the first digit is 0 or 1, the second digit allows all 10 digits, but if the first digit is 2, the second digit must be between 0 and 3. In regex syntax, this can be expressed as ‹ 2[0-3]|[01]?[0-9] ›.

How do I match a regex pattern?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


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

This may work better:

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

Regular Expressions for Time

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

      /^(0?[1-9]|1[0-2]):[0-5][0-9]$/
    
  • 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


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)


You can use this one 24H, seconds are optional

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

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

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

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

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