O'Reilly logo

Regular Expressions Cookbook, 2nd Edition by Steven Levithan, Jan Goyvaerts

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 an optional 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

See Recipe 4.14 for coverage of U.S. ZIP codes, and Recipe 4.16 for U.K. postcodes.

Recipe 4.17 explains how to determine whether something looks like a P.O. box address, in case you need to treat P.O. boxes differently than normal street addresses.

Canada Post offers a web page to look up postal codes at http://www.canadapost.ca/cpotools/apps/fpc/personal/findByCity.

Techniques used in the regular expressions in this recipe are discussed in Chapter 2. Recipe 2.3 explains character classes. Recipe 2.4 explains that the dot matches any character. Recipe 2.5 explains anchors. Recipe 2.12 explains repetition. Recipe 2.16 explains lookaround.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required