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$/The problem
Check that a string is a time of day in 24-hour HH:MM form.
How it reads
Follow the line from left to right — every path you can trace is a string this pattern matches.
^(?:[01]\d|2[0-3]):[0…In order:^The start of the text (or of a line with the m flag)(?:[01]\d|2[0-3])Group (not captured):[01]\d|2[0-3]Any one of these alternatives:[01]\dIn order:[01]Any one of: "0" or "1"\dA digit2[0-3]In order:2The character "2"[0-3]Any one of: "0" to "3":The character ":"[0-5]Any one of: "0" to "5"\dA digit$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.