How the pattern works
| Part | Meaning |
|---|---|
[ABCEGHJ-NPRSTVXY] | First letter: D, F, I, O, Q, U, W and Z are never used |
\d | A digit |
[ABCEGHJ-NPRSTV-Z] | A letter (D, F, I, O, Q, U are excluded) |
? | Optional space |
\d[ABCEGHJ-NPRSTV-Z]\d | Digit, letter, digit |
Code examples
JavaScript
const re = /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z] ?\d[ABCEGHJ-NPRSTV-Z]\d$/;
re.test(value); // true or falsePython
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.