UK Postcode Breakdown RegEX

UK postcodes are broken down/divided into 4 levels: Areas, Districts, Sectors, and Units.

For G12 8QH the breakdown is:
Area – G
District – G12
Sector – G12 8
Unit – G12 8QH

See my previous post:
UK Postcode Format Breakdown/

This is just a note of the RegEX strings to extract these, which can be used in QGIS, or PostgreSQL. These are a bit complex for most datasets, but should work independent on whether spaces and how many were used between the in and out codes. Should also work for London postcodes.

Area: G
RegEX: ^[a-zA-Z][a-zA-Z]?
PostgreSQL: substring(postcode, '^[a-zA-Z][a-zA-Z]?')
QGIS: regexp_substr("postcode" , '(^[a-zA-Z][a-zA-Z]?)')

UK Postcode Area UK Postcode Area

District: G12
This is actually pretty hard to do.

UK Postcode District UK Postcode District

Sector: G12 8
RegEX: ^[a-zA-Z]+\d\d?[a-zA-Z]?\s*\d+
PostgreSQL: substring(postcode, '^[a-zA-Z]+\d\d?[a-zA-Z]?\s*\d+')
QGIS: regexp_substr("postcode" , '(^[a-zA-Z]+\\d\\d?[a-zA-Z]?\\s*\\d+)')

UK Postcode Sector UK Postcode Sector

Unit: G12 8QH
postcode…

I’ll let you figure this one out.