4.15. Validate Canadian Postal Codes

Problem

You want to check whether a string is a Canadian postal code.

Solution

^(?!.*[DFIOQU])[A-VXY][0-9][A-Z][0-9][A-Z][0-9]$
Regex options: None
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby

Discussion

The negative lookahead at the beginning of this regular expression prevents D, F, I, O, Q, or U anywhere in the subject string. The [A-VXY] character class further prevents W or Z as the first character. Aside from those two exceptions, Canadian postal codes simply use an alternating sequence of six alphanumeric characters with a space in the middle. For example, the regex will match K1A 0B1, which is the postal code for Canada Post’s Ottawa headquarters.

See Also

Recipes 4.14, 4.16, and 4.17

Get Regular Expressions Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.