Regex for a 24-hour time (HH:MM)
^(?:[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.
JavaScript ✓PCRE ✓
No catastrophic-backtracking patterns found. (A heuristic check: nested and adjacent repeats, overlapping alternatives.)
^Start of the stringanchor(?:…)Non-capturing group: groups without rememberinggroup|Either of 2 alternatives, tried left to right; the first that leads to an overall match winsalternation- Alternative 1:
[01]One character: '0' or '1'character class\dA digit (0-9)character type- Alternative 2:
2The character '2' literallyliteral[0-3]One character: '0' to '3'character class:The character ':' literallyliteral[0-5]One character: '0' to '5'character class\dA digit (0-9)character type$End of the stringanchor
Examples
Checked at build time in JavaScript and in Python's re.
| Input | Matches? |
|---|---|
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
/^(?:[01]?\d|2[0-3]):[0-5]\d$/Allows a single-digit hour such as9:30./^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/Optional seconds:HH:MMorHH:MM:SS./^(?:0?[1-9]|1[0-2]):[0-5]\d\s?[AP]M$/i12-hour clock with AM or PM.
Gotchas
24:00fails. Earlier editions of ISO 8601 allowed it to mean the end of a day, and some schedules use it for closing time. Add|24:00if you need it.- Seconds are not allowed. Use the variant with
(?::[0-5]\d)?to make them optional. - Leap seconds such as
23:59:60are valid in RFC 3339 timestamps. Almost nothing produces them, but a strict[0-5]\dfor seconds rejects them. - For cron schedules, the hour and minute are separate fields. See cron expressions.
Related explainers
- Regex for a YYYY-MM-DD dateA regex for ISO 8601 calendar dates (YYYY-MM-DD) with month and day ranges, and why you still have to...
- Regex for digits only, integers and decimalsRegexes for digits only, signed integers and decimal numbers, with the edge cases: leading zeros, a bare...
- Regex for a hex color codeA regex for CSS hex colors in #rgb and #rrggbb form, plus the 4- and 8-digit forms with alpha, and the...