# Regex for UK Postcodes

> UK postcode regex for formats like SW1A 1AA, M1 1AE and B33 8TH, with an optional space. Token-by-token breakdown, examples and useful variations.

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

UK postcodes have an outward code (area and district, like SW1A or M1) and an inward code (sector and unit, like 1AA). This pattern covers all six standard shapes, with the space optional and case ignored. It checks the shape, not the specific letters Royal Mail allows in each position.

## Token by token

| Token | Meaning |
|---|---|
| `^` | start of string |
| `[A-Z]{1,2}` | one or two area letters (M, SW) |
| `\d` | the district digit |
| `[A-Z\d]?` | an optional second district character (the A in SW1A, the 3 in B33) |
| ` ?` | an optional space between the outward and inward codes |
| `\d[A-Z]{2}` | the inward code: a digit and two letters |
| `$` | end of string (the i flag makes letters case-insensitive) |

## Examples

- ✓ matches: `SW1A 1AA`
- ✓ matches: `M1 1AE`
- ✓ matches: `B33 8TH`
- ✓ matches: `cr26xh`
- ✓ matches: `EC1A 1BB`
- ✗ does not match: `SW1A 1A`
- ✗ does not match: `123 4AB`
- ✗ does not match: `SW1A-1AA`

## Variations

- `^(?:[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}|GIR ?0AA)$` — also accept GIR 0AA, the historic Girobank special case
- `^[A-Z]{1,2}\d[A-Z\d]?$` — outward code only (SW1A), for district-level lookups

## FAQ

### How should I store postcodes?

Normalise them: uppercase, remove spaces, then insert one space before the last three characters. The inward code is always exactly three characters, so that rule is reliable.

### Does this reject every invalid postcode?

No. It checks the shape, so some impossible combinations pass. For certainty, look postcodes up in Royal Mail's PAF or the free ONS Postcode Directory.

## Related patterns

- [Regex for US ZIP Codes](https://www.devkult.com/regex/us-zip-code.md)
- [Regex for Phone Number Validation](https://www.devkult.com/regex/phone-number.md)
- [Regex for Alphanumeric Strings](https://www.devkult.com/regex/alphanumeric.md)

Open the interactive page: https://www.devkult.com/regex/uk-postcode