Regular Expressions 101

Community Patterns

Thorough UK Postcode Validator with In/Out code capture groups

3

Regular Expression
Python

r"
([A-PR-UWYZ](?:[A-HK-Y][0-9](?:[0-9]|[ABEHMNPRV-Y])?|[0-9]([0-9]|[A-HJKPSTUW])?)) ?([0-9][ABD-HJLNP-UW-Z]{2})
"
gi

Description

A more thorough UK postcode validator tested against all UK postcodes on a regular basis, but excluding the special GIRO postcode case out of personal preference.

Additionally has capture groups for the In-code and Out-code sections.

Requires case insensitive matching.

Submitted by Chris G - 7 years ago