breakitdown

Regex for a 24-hour time (HH:MM)

Answer

^(?:[01]\d|2[0-3]):[0-5]\d$ matches 00:00 through 23:59. The hour is either 00-19 ([01]\d) or 20-23 (2[0-3]), and minutes are 00-59.

flags: g all matches · i ignore case · m ^ $ per line · s . matches newlines · u Unicode

JavaScript ✓PCRE ✓

No catastrophic-backtracking patterns found. (A heuristic check: nested and adjacent repeats, overlapping alternatives.)

  1. ^Start of the stringanchor
  2. (?:…)Non-capturing group: groups without rememberinggroup
  3. |Either of 2 alternatives, tried left to right; the first that leads to an overall match winsalternation
  4. Alternative 1:
  5. [01]One character: '0' or '1'character class
  6. \dA digit (0-9)character type
  7. Alternative 2:
  8. 2The character '2' literallyliteral
  9. [0-3]One character: '0' to '3'character class
  10. :The character ':' literallyliteral
  11. [0-5]One character: '0' to '5'character class
  12. \dA digit (0-9)character type
  13. $End of the stringanchor

Examples

Checked at build time in JavaScript and in Python's re.

InputMatches?
00:00✓ match
09:30✓ match
23:59✓ match
24:00✗ no match
9:30✗ no match
12:60✗ no match
12:5✗ no match
12:30:45✗ no match
1230✗ no match
7:30 PM✗ no match

Try your own text

One string per line: each line is tested on its own (the m flag is added here).

How it works

Hours split into two branches because the allowed second digit depends on the first. After 0 or 1, any digit works. After 2, only 0-3 does. Minutes are simpler: the tens digit is 0-5 and the units digit is anything.

Leading zeros are required here, which matches ISO 8601 and the value an <input type="time"> submits. If people type times by hand, accept 9:30 with the variant below and pad it yourself.

Variants

Gotchas

Related explainers

← Explain any regular expression