REGEXVAULTv2.0
Localization/Postal Codes
Verified Safe

Canadian Postal Code Regex for Python

/^([ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ])\s?([0-9][ABCEGHJKLMNPRSTVWXYZ][0-9])$/i

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching canadian postal code, ported and verified for Python. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.

Python Implementation

Python
# Canadian Postal Code
# ReDoS-safe | RegexVault — Localization > Postal Codes

import re

canadian_postal_code_pattern = re.compile(r'^([ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ])\s?([0-9][ABCEGHJKLMNPRSTVWXYZ][0-9])$')

def validate_canadian_postal_code(value: str) -> bool:
    return bool(canadian_postal_code_pattern.fullmatch(value))

# Example
print(validate_canadian_postal_code("K1A 0B1"))  # True

Test Cases

Matches (Valid)
Rejects (Invalid)
K1A 0B1K1A 0B
M5V 3L9K1A0B12
V6B 1G4Z1A 0B1
T2P 3C3K1A OB1
K1A0B1D1A 0B1

When to use this pattern

This pattern is drawn from the Localization > Postal Codes category and carries a ReDoS-safe certification. That matters for Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.

Common Pitfalls

The FSA (Forward Sortation Area, first 3 characters) uniquely identifies a delivery area. The LDU (Local Delivery Unit, last 3) narrows to a block. The boundary between FSA and LDU is always a space.

Technical Notes

First letter identifies the province. Invalid first letters: D, F, I, O, Q, U, W (excluded because they resemble digits in some fonts or were reserved). The letter D and I are also excluded from all positions for readability.

Have a pattern that belongs in the vault?

Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.

Submit a Pattern