UK Postcode Regex

^[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}$

Validate UK postcodes in standard formats like SW1A 1AA or M1 1AE.

Test This Pattern →

Pattern Breakdown

Understanding the regex pattern ^[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}$:

  • ^ - Start of string
  • $ - End of string
  • ? - Optional (zero or one)
  • [...] - Character class
  • {n,m} - Quantifier (n to m times)

Examples

Input Result Explanation
SW1A 1AA ✓ Match London postcode
M1 1AE ✓ Match Manchester postcode
EC1A 1BB ✓ Match Central London

Code Examples

JavaScript

JavaScript
const pattern = /^[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}$/;
const text = "SW1A 1AA";

// Test if string matches
if (pattern.test(text)) {
  console.log("Valid!");
}

// Extract matches
const matches = text.match(pattern);
console.log(matches);

Python

Python
import re

pattern = r'^[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}$'
text = "SW1A 1AA"

# Test if string matches
if re.match(pattern, text):
    print("Valid!")

# Find all matches
matches = re.findall(pattern, text)
print(matches)

PHP

PHP
<?php
$pattern = '/^[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}$/';
$text = "SW1A 1AA";

// Test if string matches
if (preg_match($pattern, $text)) {
    echo "Valid!";
}

// Find all matches
preg_match_all($pattern, $text, $matches);
print_r($matches);
?>

Java

Java
import java.util.regex.*;

String pattern = "^[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}$";
String text = "SW1A 1AA";

Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);

if (m.matches()) {
    System.out.println("Valid!");
}

Use Cases

Common applications: UK address forms, Royal Mail integration

Frequently Asked Questions

What is the regex pattern for uk postcode regex?
The regex pattern is: ^[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}$. Validate UK postcodes in standard formats like SW1A 1AA or M1 1AE.
How do I use the uk postcode regex pattern in JavaScript?
In JavaScript: const regex = new RegExp('^[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}$'); or const regex = /^[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}$/;
Does this pattern work in Python?
Yes, use: import re; pattern = re.compile(r'^[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}$') in Python. Most regex patterns are cross-language compatible.
What are common use cases for uk postcode regex?
UK address forms, Royal Mail integration

Related Regex Patterns

More Regex Tools

GetDevUtils offers a suite of developer tools including: