devkult_
tools29converters34
home/regex/uk-postcode

Regex for UK Postcodes

UK postcodes have an outward code (area and district, like SW1A or M1) and an inward code (sector and unit, like 1AA). This pattern covers all six standard shapes, with the space optional and case ignored. It checks the shape, not the specific letters Royal Mail allows in each position.

/^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i

How it works, token by token

TokenMeaning
^start of string
[A-Z]{1,2}one or two area letters (M, SW)
\dthe district digit
[A-Z\d]?an optional second district character (the A in SW1A, the 3 in B33)
?an optional space between the outward and inward codes
\d[A-Z]{2}the inward code: a digit and two letters
$end of string (the i flag makes letters case-insensitive)

What it matches

✓SW1A 1AA
✓M1 1AE
✓B33 8TH
✓cr26xh
✓EC1A 1BB
✗SW1A 1A
✗123 4AB
✗SW1A-1AA

Try it live

One candidate per line — the m flag makes the ^ and $ anchors apply to each line. Edit anything; it runs in your browser.

/

Variations

^(?:[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}|GIR ?0AA)$also accept GIR 0AA, the historic Girobank special case
^[A-Z]{1,2}\d[A-Z\d]?$outward code only (SW1A), for district-level lookups

Frequently asked questions

How should I store postcodes?

Normalise them: uppercase, remove spaces, then insert one space before the last three characters. The inward code is always exactly three characters, so that rule is reliable.

Does this reject every invalid postcode?

No. It checks the shape, so some impossible combinations pass. For certainty, look postcodes up in Royal Mail's PAF or the free ONS Postcode Directory.

Related patterns

Building something custom? The regex tester gives you live match highlighting for any pattern.