Regex for time HH:MM
24-hour time matches ^([01]\d|2[0-3]):[0-5]\d$ (00:00 to 23:59). 12-hour time with AM or PM matches ^(1[0-2]|0?[1-9]):[0-5]\d ?[AaPp][Mm]$. Add (?::[0-5]\d)? before the $ to allow optional seconds.
Syntax
/^([01]\d|2[0-3]):[0-5]\d$/Examples
["09:30", "23:59", "24:00", "9:30"].map(s => /^([01]\d|2[0-3]):[0-5]\d$/.test(s))Result: [true, true, false, false]
24:00 is out of range and 9:30 lacks the leading zero.
["9:05 PM", "12:30am", "13:00 PM"].map(s => /^(1[0-2]|0?[1-9]):[0-5]\d ?[AaPp][Mm]$/.test(s))Result: [true, true, false]
/^([01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/.test("23:59:59")Result: true
Optional seconds in a non-capturing group.
"started 08:15, ended 17:42".match(/\b([01]\d|2[0-3]):[0-5]\d\b/g)Result: ["08:15", "17:42"]
Common mistakes
- \d{2}:\d{2} accepts 99:99; use the hour and minute ranges.
- Allowing 24:00, which is valid only in a few standards (ISO 8601 end-of-day); most parsers reject it.
- Forgetting 0? in the 12-hour pattern, so 9:30 PM fails.
- Using (\d) capturing groups when you only need the match; switch to (?:...) or read the right group index.
Practice Regex for time HH:MM
These drills check your answer on live data, free, no account needed.
- 24-hour times HH:MMThe whole line must match. Match a 24-hour time from 00:00 to 23:59 with two-digit hours and minutes.
- 12-hour times with AM or PMThe whole line must match. Match an hour from 1 to 12 with no leading zero, a colon, two-digit minutes, an optional space and AM or PM in capitals.
- Alternation: cat, dog or birdThe whole line must match. Match exactly one of the words cat, dog or bird.
Questions
What is the regex for time with seconds?
^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$ requires seconds; wrap the last part as (?::[0-5]\d)? to make it optional.
How do I match 12-hour time without a leading zero?
Use 0?[1-9] for hours 1 to 9 and 1[0-2] for 10 to 12: ^(1[0-2]|0?[1-9]):[0-5]\d ?(?:AM|PM)$ with the i flag.
What is the regex for a duration like 1h 30m?
^(?:(\d+)h)? ?(?:(\d+)m)?$ captures hours and minutes separately; both parts are optional so 45m and 2h also match.
Related
- Regex for date YYYY-MM-DDA regex for ISO dates like 2024-03-15 with month and day ranges, named groups for year, month and day, reformatting MM/DD/YYYY, and what a regex cannot check.
- Alternation |How the pipe works, why ^cat|dog$ does not do what it looks like, how to group alternatives, and why option order matters when one is a prefix of another.
- Ranges in character classesHow character ranges work by code point, how to combine them, the invalid [a-Z] and surprising [A-z], and how to express numeric ranges with alternation.
- Optional with ?How ? makes a character optional, making a whole sequence optional with a group, what the capture holds when the group is absent, and the ? that means lazy.