Regular Expressions 101

Community Patterns

Better version of UK postcode

2

Regular Expression
PCRE (PHP <7.3)

/
^(A[BL]|B[ABDFHLNRSTX]?|C[ABFHMORTVW]|D[ADEGHLNTY]|E[CHNX]?|F[KY]|G[LUY]?|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]?|M[EKL]?|N[EGNPRW]?|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKLMNOPRSTWY]?|T[ADFNQRSW]|UB|W[ACDFNRSV]?|YO|ZE)(\d[\dA-Z]?) ?(\d)([A-Z]{2})$
/
gm

Description

This UK postcode regex will match all variants of postcode formats including inner London postcodes (eg SW1A), with optional space (both AL11XP and AL1 1XP are valid)

It will reject any postcode that does not specify a valid postcode area.

Each part of the postcode is also captured into a capture group as follows: group 1: POSTCODE AREA group 2: POSTCODE DISTRICT group 3: POSTCODE SECTOR group 4: POSTCODE UNIT

Submitted by anonymous - 6 years ago