The Pattern
``regex
^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$
`
Flags: gm ā multiline, so ^ and $ anchor to each line rather than the whole input.
What It Accepts and Rejects
| Input | Result |
|---|---|
09:30 | ā matches |
23:59:59 | ā matches |
24:00 | ā rejected |
7:05 | ā rejected |
Ranges Come From Digit Classes, Not Numbers
Regex has no concept of "less than 24". The hour is written (?:[01]\d|2[0-3]), which is
two branches: any digit after 0 or 1, and only 0ā3 after a 2. Minutes are [0-5]\d by the
same logic.
That is why 24:00 is rejected ā neither branch accepts a 4 following a 2 ā and why
7:05 is rejected too, since the pattern requires a leading zero.
The optional (?::[0-5]\d)? makes seconds optional, so both 09:30 and 23:59:59 pass.
The Limits of This Pattern
Real time strings carry more than this: 23:59:60 is a legal leap second, and offsets
(+02:00) and fractional seconds appear in ISO 8601 timestamps. Validating a time also
tells you nothing about whether it exists in a given time zone ā 02:30 does not exist on a
spring-forward date, and a regex will happily accept it.
Testing Before Shipping
A regex that has only been tried against inputs you expect to match is untested. Every
pattern needs three kinds of case:
1. Valid inputs that should match, including the awkward-but-legal ones.
2. Invalid inputs that should not, especially near-misses that differ by one character.
3. Adversarial inputs ā very long strings, unusual Unicode, and nesting that could
trigger catastrophic backtracking.
Paste your own examples into the tester above and watch which lines highlight. A pattern
that matches everything you throw at it is usually too permissive rather than correct.
Catastrophic Backtracking
Nested quantifiers over overlapping character classes ā (a+)+, (\w+\s?)* ā can take
exponential time on a non-matching input. On a server that is a denial-of-service bug, not a
performance issue. If a pattern is applied to user input, bound the input length first and
prefer explicit alternation over nested repetition.
Anchors, Greediness and Backtracking
Three behaviours account for most regex surprises, and this pattern shows all three.
Anchors. ^ and $ pin the match to the start and end of the input. Without them,
\d{3} matches the 123 inside abc123def. With m in the flags ā as here ā they
pin to each *line* instead, which is what lets one pattern be tested against a list.
Greediness. .* takes as much as it can and gives back only when forced; .*? takes
as little as possible. On , the pattern <.*> matches the whole string and
<.*?> matches just .
Testing It Properly
`javascript
const pattern = /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/gm;