Regex for Canadian postal code

Use /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z] ?\d[ABCEGHJ-NPRSTV-Z]\d$/ to check that a whole string is a valid for Canadian postal code. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z] ?\d[ABCEGHJ-NPRSTV-Z]\d$/
Open in Regex Tester
InputResult
K1A 0B1✓ Match
M5V3L9✓ Match
H2X 1Y4✓ Match
D1A 0B1✗ No match
K1A-0B1✗ No match
12345✗ No match
k1a 0b1✗ No match

How the pattern works

PartMeaning
[ABCEGHJ-NPRSTVXY]First letter: D, F, I, O, Q, U, W and Z are never used
\dA digit
[ABCEGHJ-NPRSTV-Z]A letter (D, F, I, O, Q, U are excluded)
?Optional space
\d[ABCEGHJ-NPRSTV-Z]\dDigit, letter, digit

Code examples

JavaScript

const re = /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z] ?\d[ABCEGHJ-NPRSTV-Z]\d$/;
re.test(value); // true or false

Python

import re

bool(re.fullmatch(r'[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z] ?\d[ABCEGHJ-NPRSTV-Z]\d', value))

PHP

preg_match('/^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z] ?\d[ABCEGHJ-NPRSTV-Z]\d$/', $value) === 1;

Notes and limitations

Upper-case the input first if you want to accept lower-case entries — the pattern is case-sensitive on purpose so it can rule out the unused letters.

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex for Canadian postal code?
/^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z] ?\d[ABCEGHJ-NPRSTV-Z]\d$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: K1A 0B1, M5V3L9, H2X 1Y4. 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.