|Regex options: None|
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.
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.