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}$/iHow it works, token by token
| Token | Meaning |
|---|---|
| ^ | start of string |
| [A-Z]{1,2} | one or two area letters (M, SW) |
| \d | the 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 1AAM1 1AEB33 8THcr26xhEC1A 1BBSW1A 1A123 4ABSW1A-1AATry 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 lookupsFrequently 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.
Building something custom? The regex tester gives you live match highlighting for any pattern.