Regex for UK Postcode — Pattern Explained with Examples
DodaTech
Updated Jun 20, 2026
2 min read
UK postcodes are alphanumeric codes used by Royal Mail to sort mail. This pattern validates the standard format: an outward code (area and district) followed by a space and an inward code (sector and unit).
The Pattern
/^[A-Z]{1,2}[0-9][A-Z0-9]?\s?[0-9][A-Z]{2}$/iPattern Breakdown
| Part | Meaning |
|---|---|
^ | Start-of-string anchor |
[A-Z]{1,2} | One or two alphabetic characters (postcode area) |
[0-9] | Single digit (district) |
[A-Z0-9]? | Optional alphanumeric character (sub-district) |
\s? | Optional whitespace separator |
[0-9] | Single digit (sector) |
[A-Z]{2} | Two alphabetic characters (unit) |
$ | End-of-string anchor |
i | Case-insensitive flag |
Matches
SW1A 1AAEC2R 8AHM1 1AEB33 8THCR2 6XH
Does NOT Match
SW1A-1AA12345SW1ABCDEFA11AAASW1A 1A
Language Examples
JavaScript
const ukPostcodeRegex = /^[A-Z]{1,2}[0-9][A-Z0-9]?\s?[0-9][A-Z]{2}$/i;
console.log(ukPostcodeRegex.test('SW1A 1AA')); // true
console.log(ukPostcodeRegex.test('12345')); // false
Python
import re
pattern = r'^[A-Z]{1,2}[0-9][A-Z0-9]?\s?[0-9][A-Z]{2}$'
print(bool(re.match(pattern, 'SW1A 1AA', re.IGNORECASE))) # True
print(bool(re.match(pattern, '12345', re.IGNORECASE))) # FalseCommon Pitfalls
- The space between outward and inward code is optional in some formats but recommended — this pattern uses
\s?for flexibility - Postcode formats vary significantly:
M1 1AE(Manchester) has a single-letter area and single-digit district, whileSW1A 1AAhas two letters and a letter-digit district - London districts use numeric codes (EC1, EC2, etc.) that this pattern matches correctly
- BFPO (British Forces Post Office) addresses use a different format (
BFPO 1234) not covered by this pattern - Some special postcodes (e.g.,
GIR 0AA) are exceptions that may not match this general pattern
Real-World Use Cases
- E-commerce checkout — validate UK shipping addresses before calculating delivery costs
- CRM data cleaning — standardize and validate postcode entries in customer databases
- Postcode lookup services — pre-validate user input before querying a postcode API to reduce API costs
FAQ
Related Patterns
Regex for Canadian Postal Code Regex for ZIP/Postal Code
Previous
Regex for CVV — Pattern Explained with Examples
Next
Regex for Canadian Postal Code — Pattern Explained with Examples
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro