Regex and cron

Regex for UK Postcodes

Accept every real UK postcode format while rejecting letters Royal Mail never uses.

  • Free foreverNo trial, no paywall, no usage limits.
  • No sign-upOpen the page and start. We never ask for an email to use a tool.
  • PrivateEverything runs in your browser. Your input is never uploaded or stored on our servers.
  • Works offlineOnce the page has loaded, the tool keeps working without a connection.

Pattern

/^(?:GIR ?0AA|[A-PR-UWYZ](?:\d{1,2}|[A-HK-Y]\d{1,2}|\d[A-HJKPSTUW]|[A-HK-Y]\d[ABEHMNPRV-Y]) ?\d[ABD-HJLNP-UW-Z]{2})$/i
  • i ignore caseCase-insensitive: /abc/i also matches "ABC" and "aBc".

Regular expression

JavaScript syntax, run by your browser's own engine in a background worker. Press / anywhere to jump here.
Reset to the original pattern and examplesShow cheat sheet: click any token to insert itCopy pattern
Find every match instead of stopping at the first. Needed for matchAll() and for replacing all occurrences.Case-insensitive: /abc/i also matches "ABC" and "aBc".^ and $ match at the start and end of every line, not just the whole string. Use it to test one value per line.Lets . match line breaks too. Without it, . stops at \n and \r.Treats the pattern as Unicode code points: enables \p{…} property escapes and \u{…}, makes emoji count as one character, and rejects sloppy escapes.Only matches starting exactly at lastIndex (position 0 here), never further along. Useful for tokenizers that consume input piece by piece.Records the start and end index of every capture group (match.indices). The tester always shows group positions, so this only changes your code.The upgraded unicode mode (ES2024): set operations like [\p{L}--[a-z]] and [A&&B], string properties like \p{RGI_Emoji}. Cannot be combined with u.
8 matches8 matches

Test string

Matches are highlighted as you type, in alternating colors. Click inside a match (or hover its row below) to color its capture groups.
8 matchesClear test string

Explanation

Every part of the pattern in plain English. Hover a row to highlight that part of the pattern.
Copy explanation

Loading the explainer…

Every match with its position and capture groups.Preview a replacement with $1, $<name> and $& references, then copy the result.Copy a ready-to-run snippet for JavaScript, Python, Go, C#, PHP or Dart.

Matches

Named groups are shown by name. undefined means the group did not take part in that match.
Copy matches as JSONDownload matches.csv
#MatchPosition
1SW1A·1AA0–8
2EC1A·1BB9–17
3W1A·1AA18–25
4M1·1AE26–32
5B33·8TH33–40
6CR2·6XH41–48
7DN55·1PT49–57
8sw1a1aa58–65

Need a secure web app built around this? Talk to our team

Quick answer

This UK postcode regex covers all six outward formats (A9, A99, A9A, AA9, AA99 and AA9A, such as M1, B33, W1A, CR2, DN55 and EC1A), an optional space, and the inward code of a digit plus two letters. It applies Royal Mail's letter rules, so Q, V and X never start a postcode and C, I, K, M, O and V never appear in the last two letters. Use the i flag to accept lowercase.

  • Tested examples
  • Token-by-token breakdown
  • Code in 5 languages
  • Live tester

How to use the UK postcode regex

  1. 1Copy the pattern with Copy pattern in the tester, or take a ready-made snippet for your language from the code section below.
  2. 2Check the sample lines in Test string: every line the UK postcode regex accepts is highlighted, rejected lines stay plain.
  3. 3Paste your own values one per line to see which pass, and read Explanation for what each part of the pattern does.
  4. 4Open the Code tab for JavaScript, Python, Go, C#, PHP or Dart with the pattern translated and escaped.
  5. 5Validate again on the server: client-side checks give users quick feedback, not security.

How does the UK postcode regex work?

Read it left to right. Each piece below matches one part of the input:

  • GIR ?0AA| A special case: GIR 0AA, a non-geographic postcode kept for historical reasons.
  • [A-PR-UWYZ] The area's first letter. Q, V and X are never used here.
  • \d{1,2} Formats A9 and A99, such as M1 and B33.
  • |[A-HK-Y]\d{1,2} Formats AA9 and AA99: the second letter is never I, J or Z (CR2, DN55).
  • |\d[A-HJKPSTUW] Format A9A, as in W1A.
  • |[A-HK-Y]\d[ABEHMNPRV-Y] Format AA9A, as in EC1A and SW1A.
  • ? An optional space between the outward and inward codes.
  • \d[ABD-HJLNP-UW-Z]{2} The inward code: a digit and two letters, never C, I, K, M, O or V.

Flags: i (ignore case).

Which strings does the UK postcode regex match?

The whole input must match, from the first character to the last. Every row below is checked against the pattern by our automated test suite before each release.

InputMatches?Why
SW1A 1AAYesBuckingham Palace: format AA9A.
EC1A 1BBYesCity of London: AA9A.
W1A 1AAYesBBC Broadcasting House: A9A.
M1 1AEYesManchester: A9.
B33 8THYesBirmingham: A99.
CR2 6XHYesCroydon: AA9.
DN55 1PTYesDoncaster: AA99.
sw1a1aaYesLowercase and no space, thanks to the i flag and the optional space.
QA1 1AANoQ is never the first letter.
SW1A 1CANoC is never used in the inward code.
SW1A-1AANoA hyphen instead of a space.
SW1A 1AAANoThree letters in the inward code.
12345NoA US-style number.

How is a UK postcode structured?

Every postcode has two halves. The outward code (SW1A) identifies the area and district and is used to sort mail to a delivery office; the inward code (1AA) narrows it down to a street or part of one. The inward code is always a digit plus two letters, which is why the space can be omitted and still be inserted reliably: it always comes before the last three characters.

const formatPostcode = (s) => {
  const compact = s.replace(/\s+/g, "").toUpperCase();
  return compact.slice(0, -3) + " " + compact.slice(-3);
};
formatPostcode("sw1a1aa"); // "SW1A 1AA"

Store postcodes in this canonical uppercase, single-space form so lookups and deduplication work.

Does this regex cover British Forces and overseas territories?

It covers the standard Royal Mail formats used across the UK, which also fit the Isle of Man, Jersey and Guernsey (IM, JE, GY areas). Special cases need additional alternatives:

  • British Forces Post Office: BFPO followed by a number, such as BFPO 801.
  • Overseas territories with UK-style codes, such as ASCN 1ZZ (Ascension) and TDCU 1ZZ (Tristan da Cunha), use four-letter outward codes.

A postcode in the right format can still be unassigned. For address capture, offer a postcode lookup backed by Royal Mail's Postcode Address File so people pick a real address rather than typing one.

How do I use the UK postcode regex in JavaScript, Python, Go, C# and PHP?

The pattern is translated for each engine rather than pasted as is: named groups, anchors, escapes, shorthand classes and flags are adjusted so each snippet behaves as closely to the JavaScript version as its engine allows. Differences that remain (Go's RE2 has no lookarounds or backreferences, for example) are called out under each one. The Code tab in the tester above also exports Dart, and updates as you edit the pattern.

JavaScript and TypeScript

const regex = /^(?:GIR ?0AA|[A-PR-UWYZ](?:\d{1,2}|[A-HK-Y]\d{1,2}|\d[A-HJKPSTUW]|[A-HK-Y]\d[ABEHMNPRV-Y]) ?\d[ABD-HJLNP-UW-Z]{2})$/i;

function isValid(value) {
  return regex.test(value);
}

console.log(isValid("SW1A 1AA"));

Python

import re

pattern = re.compile(r"^(?:GIR ?0AA|[A-PR-UWYZ](?:[0-9]{1,2}|[A-HK-Y][0-9]{1,2}|[0-9][A-HJKPSTUW]|[A-HK-Y][0-9][ABEHMNPRV-Y]) ?[0-9][ABD-HJLNP-UW-Z]{2})\Z", re.IGNORECASE)

def is_valid(value: str) -> bool:
    return pattern.search(value) is not None

print(is_valid("SW1A 1AA"))
  • \d and \w are written as [0-9] and [A-Za-z0-9_] because in Python they also match digits and letters from other scripts.
  • JavaScript's $ only matches at the very end of the string. Python's $ also matches before a trailing newline, so the pattern uses \Z instead.

Go

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`(?i)^(?:GIR ?0AA|[A-PR-UWYZ](?:\d{1,2}|[A-HK-Y]\d{1,2}|\d[A-HJKPSTUW]|[A-HK-Y]\d[ABEHMNPRV-Y]) ?\d[ABD-HJLNP-UW-Z]{2})$`)
	fmt.Println(re.MatchString("SW1A 1AA"))
}

C#

using System;
using System.Text.RegularExpressions;

// The timeout stops a pathological input from hanging the thread (ReDoS).
var regex = new Regex(@"^(?:GIR ?0AA|[A-PR-UWYZ](?:[0-9]{1,2}|[A-HK-Y][0-9]{1,2}|[0-9][A-HJKPSTUW]|[A-HK-Y][0-9][ABEHMNPRV-Y]) ?[0-9][ABD-HJLNP-UW-Z]{2})\z", RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));
Console.WriteLine(regex.IsMatch("SW1A 1AA"));
  • \d and \w are written as [0-9] and [A-Za-z0-9_] because in .NET they also match digits and letters from other scripts.
  • JavaScript's $ only matches at the very end of the string. .NET's $ also matches before a trailing newline, so the pattern uses \z instead.

PHP

<?php

$pattern = '/^(?:GIR ?0AA|[A-PR-UWYZ](?:\d{1,2}|[A-HK-Y]\d{1,2}|\d[A-HJKPSTUW]|[A-HK-Y]\d[ABEHMNPRV-Y]) ?\d[ABD-HJLNP-UW-Z]{2})$/iD';

function isValid(string $value, string $pattern): bool
{
    return preg_match($pattern, $value) === 1;
}

var_dump(isValid('SW1A 1AA', $pattern));
  • The D modifier makes $ match only at the very end, like JavaScript (PCRE's $ also matches before a trailing newline).

Browse all 25 patterns in the regex pattern library, or build your own in the regex tester.

Frequently asked questions

Not for validation. This pattern accepts it with or without the space, because the inward code is always the last three characters. Insert the space before the last three characters when you display or store it.
No. They are written in uppercase by convention, so match case-insensitively and convert to uppercase before storing.
A non-geographic postcode historically used by the Girobank, kept as a special case in the official format rules. The pattern accepts it explicitly.

Last updated by the Playxoft engineering team.

From the engineers who built this tool

Building something bigger than a quick fix?

Auth, payments, dashboards and security are where web apps get hard. We have shipped them many times. Share your idea and we will map out a realistic plan and estimate, free and with no obligation.

More free tools

See all tools

Regex Tester

Test regex live with highlighted matches, plain-English explanations and code export.

Open tool

Cron Expression Generator

New

Build and explain cron schedules, see the next runs in any time zone, copy platform snippets.

Open tool

SQL Formatter

Beautify or minify SQL in 12 dialects, with keyword case, indent and line:column errors.

Open tool

cURL to Python Converter

New

Convert cURL commands into Python requests or httpx code with params, json, files and auth.

Open tool

cURL to Fetch Converter

New

Turn any cURL command into JavaScript fetch() code with headers, JSON, forms and auth.

Open tool

cURL to Axios Converter

New

Convert cURL commands into an Axios request config with params, data, auth and timeouts.

Open tool