Skip to content
Regex for UK Postcode — Pattern Explained with Examples

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}$/i

Pattern Breakdown

PartMeaning
^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
iCase-insensitive flag

Matches

  • SW1A 1AA
  • EC2R 8AH
  • M1 1AE
  • B33 8TH
  • CR2 6XH

Does NOT Match

  • SW1A-1AA
  • 12345
  • SW1
  • ABCDEF
  • A11AAA
  • SW1A 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)))     # False

Common 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, while SW1A 1AA has 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

Is the space in a UK postcode required?
Royal Mail recommends the space for readability and automated sorting, but many databases store postcodes without it (e.g., SW1A1AA). This pattern makes the space optional with \s?. For strict validation, require the space with \s (without ?).
What about postcodes with a trailing space or special characters?
Trailing whitespace should be trimmed before validation. Special characters like hyphens or slashes are not valid in UK postcodes. Some formats use a space as the only allowed separator.

Related Patterns

Regex for Canadian Postal Code Regex for ZIP/Postal Code

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro