How the pattern works
| Part | Meaning |
|---|---|
(?:0?[1-9]|1[0-2]) | Hours 1–12, with an optional leading zero |
:[0-5]\d | Colon and minutes 00–59 |
? | Optional space |
[AaPp][Mm] | AM or PM in any case |
Code examples
JavaScript
const re = /^(?:0?[1-9]|1[0-2]):[0-5]\d ?[AaPp][Mm]$/;
re.test(value); // true or falsePython
import re
bool(re.fullmatch(r'(?:0?[1-9]|1[0-2]):[0-5]\d ?[AaPp][Mm]', value))PHP
preg_match('/^(?:0?[1-9]|1[0-2]):[0-5]\d ?[AaPp][Mm]$/', $value) === 1;
Notes and limitations
There is no 0:00 or 13:00 on a 12-hour clock, so both are rejected.
Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool Frequently asked questions
What is the regex for time (12-hour with AM/PM)?
/^(?:0?[1-9]|1[0-2]):[0-5]\d ?[AaPp][Mm]$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: 9:30 AM, 12:00pm, 07:15 PM. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.