DD
DevDash

Regex for Canadian Postal Code

Regex Pattern

^[A-Z]\d[A-Z] ?\d[A-Z]\d$

Canadian postal code (letter-digit-letter digit-letter-digit)

Quick Answer

The regex pattern for canadian postal code is `^[A-Z]\d[A-Z] ?\d[A-Z]\d$`. Canadian postal code (letter-digit-letter digit-letter-digit). This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.

Test Examples

InputResult
K1A 0B1✓ Matches
M5V 3A8✓ Matches
H2Y1C6✓ Matches
12345✗ No match
K1A-0B1✗ No match
k1a 0b1✗ No match

Code Examples

javascript

const regex = /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/;
const isValid = regex.test(value);

python

import re
pattern = r'^[A-Z]\d[A-Z] ?\d[A-Z]\d$'
if re.match(pattern, value):
    print("valid")

ruby

pattern = /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/
if value =~ pattern
  puts "valid"
end

php

if (preg_match('/^[A-Z]\d[A-Z] ?\d[A-Z]\d$/', $value)) {
    echo "valid";
}

java

String pattern = "^[A-Z]\\d[A-Z] ?\\d[A-Z]\\d$";
boolean isValid = value.matches(pattern);

Frequently Asked Questions

Related Regex Patterns

Want API access + no ads? Pro coming soon.