Regex patterns/Dates & times

24-hour time

Hours 00–23 and minutes 00–59, each range built from digit classes.

/^(?:[01]\d|2[0-3]):[0-5]\d$/
Open it in Rex

The problem

Check that a string is a time of day in 24-hour HH:MM form.

How it reads

startgroup[01]\d2[0-3]:[0-5]\dend

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. ^(?:[01]\d|2[0-3]):[0…In order:
  2. ^The start of the text (or of a line with the m flag)
  3. (?:[01]\d|2[0-3])Group (not captured):
  4. [01]\d|2[0-3]Any one of these alternatives:
  5. [01]\dIn order:
  6. [01]Any one of: "0" or "1"
  7. \dA digit
  8. 2[0-3]In order:
  9. 2The character "2"
  10. [0-3]Any one of: "0" to "3"
  11. :The character ":"
  12. [0-5]Any one of: "0" to "5"
  13. \dA digit
  14. $The end of the text (or of a line with the m flag)

Matches

  • 09:30
  • 23:59
  • 00:00

Does not match

  • 24:00
  • 9:30
  • 12:60
  • 12:3

Where it bites

  • The hour splits into two branches because 0–19 and 20–23 need different digit constraints. That split is the whole trick.
  • [0-5]\d covers 00–59 in two characters — a much-repeated idiom worth recognising.
  • Single-digit hours ("9:30") are rejected. Add 0? if your input is not zero-padded.

More dates & times patterns