4.16. Validate U.K. Postcodes

Problem

You need a regular expression that matches a U.K. postcode.

Solution

^[A-Z]{1,2}[0-9R][0-9A-Z]?[0-9][ABD-HJLNP-UW-Z]{2}$
Regex options: None
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby

Discussion

Postal codes in the U.K. (or postcodes, as they’re called) are composed of five to seven alphanumeric characters separated by a space. The rules covering which characters can appear at particular positions are rather complicated and fraught with exceptions. This regular expression sticks to the basic rules.

See Also

British Standard BS7666, available at http://www.govtalk.gov.uk/gdsc/html/frames/PostCode.htm, describes the U.K. postcode rules.

Recipes 4.14, 4.15, 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.