Regex for time (12-hour with AM/PM)

Use /^(?:0?[1-9]|1[0-2]):[0-5]\d ?[AaPp][Mm]$/ to check that a whole string is a valid for time (12-hour with AM/PM). Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^(?:0?[1-9]|1[0-2]):[0-5]\d ?[AaPp][Mm]$/
Open in Regex Tester
InputResult
9:30 AM✓ Match
12:00pm✓ Match
07:15 PM✓ Match
13:00 PM✗ No match
9:30✗ No match
0:30 AM✗ No match
9:30 A.M.✗ No match

How the pattern works

PartMeaning
(?:0?[1-9]|1[0-2])Hours 1–12, with an optional leading zero
:[0-5]\dColon 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 false

Python

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.