Canadian Postal Code in PY
Match Canadian postal codes in the A1A 1A1 or A1A1A1 format with valid first-letter prefixes.
Try it in the PY tester →Pattern
regexPY
[ABCEGHJ-NPRSTVXY]\d[A-Z] ?\d[A-Z]\d (flags: gi)Python (re) code
pyPython
import re
pattern = re.compile(r"[ABCEGHJ-NPRSTVXY]\d[A-Z] ?\d[A-Z]\d", re.IGNORECASE)
input_text = "K1A 0B1"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
How the pattern works
The leading character is constrained to letters actually used by Canada Post (D, F, I, O, Q, U, W, Z are excluded). Alternating letter-digit pattern, with an optional space separator.
Examples
Input
K1A 0B1Matches
K1A 0B1
Input
M5V3L9Matches
M5V3L9
Input
12345No match
—