validation

UK Postcode Regex Pattern

Validates UK postcodes in the common formats (SW1A 1AA, M1 1AE, etc.). Case-insensitive by flag. Covers ~99% of valid postcodes but doesn't check that the specific postcode exists.

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

What each part matches

^[A-Z]{1,2} — 1-2 letter area code
\d — district digit
[A-Z\d]? — optional sub-district char (letter or digit)
\s* — optional space
\d[A-Z]{2}$ — sector digit + 2 unit letters

✓ These match

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

✗ These don't

  • 1SW A1AA
  • SW1
  • SW1A1A
  • 12345

Use in your code

JavaScript

const re = /^[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}$/i;
re.test(input); // → true or false

Python

import re
re.fullmatch(r"^[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}$", input)

PHP (PCRE)

preg_match('/^[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}$/i', $input);

Go

re := regexp.MustCompile(`^[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}$`)
re.MatchString(input)

FAQ

Does this uk postcode regex work in JavaScript?
Yes. Every pattern in the Utilko regex library is tested to work in JavaScript RegExp, PCRE (PHP, Nginx), and Python `re`. Where flavor matters (lookbehind, named groups), the pattern page flags it.
How do I use this pattern?
Copy the pattern from the code block above. In JavaScript: new RegExp('^[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}$') or literal /^[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}$/i. Or click "Try in regex tester" to open it pre-loaded in Utilko's browser-based regex tester.
Should I use this for security-critical validation?
Client-side regex is fine for UX (immediate feedback on a form). For anything security-critical — payments, auth, data integrity — always re-validate server-side using the same pattern PLUS domain-specific checks (Luhn checksum for cards, actual email delivery test, DNS resolution for domains).

Related regex patterns

← All regex patterns · Regex tester · Regex cheat sheet