PatternRegex

Match a time in 24-hour format

Match HH:MM on the 24-hour clock with real bounds: hours stop at 23 and minutes at 59, so 24:00 and 18:75 fail like they should.

Last updated

Patterng
(?:[01]\d|2[0-3]):[0-5]\d
Open in Regex Tester & Builder

Matches

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

Doesn’t match

  • 24:00
  • 9:30
  • 18:75

Why it’s written this way

The hour is two alternatives, because its two digits aren't independent: 0x and 1x allow any second digit, but 2x only allows 0–3. Writing [0-2]\d instead is the classic bug — it happily accepts 27:00.

Minutes are simpler — first digit 0–5, second anything — so one class each does it.

Edge cases to know

  • Single-digit hours without a leading zero (9:30) don't match; allow them with (?:[01]?\d|2[0-3]).
  • Inside longer digit runs it can find a valid-looking substring (123:45 contains 23:45) — anchor with ^…$ when validating a whole field.
  • Seconds (HH:MM:SS) need an explicit (?::[0-5]\d)? added; this pattern stops at minutes.

Related in Patterns