Regex to Match 12-Hour Time Format

Validate 12-hour time format with AM/PM designation using this regex. Matches time values like 2:30 PM or 12:00:00 AM. Free online regex tester.

Regular Expression

/^(?:0?[1-9]|1[0-2]):[0-5]\d(?::[0-5]\d)?\s?[AaPp][Mm]$/

Token Breakdown

TokenDescription
^Anchors at the start of the string (or line in multiline mode)
(?:Start of non-capturing group
0Matches the literal character '0'
?Makes the preceding element optional (zero or one times)
[1-9]Character class — matches any one of: 1-9
|Alternation — matches the expression before OR after the pipe
1Matches the literal character '1'
[0-2]Character class — matches any one of: 0-2
)End of group
:Matches the literal character ':'
[0-5]Character class — matches any one of: 0-5
\dMatches any digit (0-9)
(?:Start of non-capturing group
:Matches the literal character ':'
[0-5]Character class — matches any one of: 0-5
\dMatches any digit (0-9)
)End of group
?Makes the preceding element optional (zero or one times)
\sMatches any whitespace character (space, tab, newline)
?Makes the preceding element optional (zero or one times)
[AaPp]Character class — matches any one of: AaPp
[Mm]Character class — matches any one of: Mm
$Anchors at the end of the string (or line in multiline mode)

Detailed Explanation

This regex validates times in the 12-hour format with AM/PM designation. Here is the token-by-token breakdown:

^ — Anchors the match at the start of the string.

(?:0?[1-9]|1[0-2]) — A non-capturing group matching valid hours (1-12). 0?[1-9] matches hours 1-9 with an optional leading zero (so both '2' and '02' are valid). 1[0-2] matches hours 10-12.

: — Matches a literal colon separating hours from minutes.

[0-5]\d — Matches valid minutes (00-59). The first digit is restricted to 0-5 and the second can be any digit.

(?::[0-5]\d)? — An optional non-capturing group matching seconds. When present, it starts with a colon followed by valid seconds (00-59). Many time displays omit seconds.

\s? — Matches an optional whitespace character between the time and the AM/PM designator. Some formats include a space (2:30 PM) while others do not (2:30PM).

[AaPp][Mm] — Matches the AM/PM designator. The first character class allows A or a and P or p, while the second allows M or m. This accepts AM, am, PM, pm, Am, Pm, and other case combinations.

$ — Anchors the match at the end of the string.

This pattern is commonly used for validating user input in scheduling applications, alarm clocks, and booking systems that use the 12-hour clock convention prevalent in the United States and several other countries.

Example Test Strings

InputExpected
2:30 PMMatch
12:00:00 AMMatch
13:00 PMNo Match
0:00 AMNo Match
11:59pmMatch

Try It — Interactive Tester

//
gimsuy
No matches found.
Pattern: 54 charsFlags: noneMatches: 0

Ctrl+Shift+C to copy regex

Customize this pattern →