Python (re)

UK Postcode in PY

Match UK postcodes in the common outward + inward format (e.g. SW1A 1AA, EC1V 9LB).

Try it in the PY tester →

Pattern

regexPY
[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}   (flags: gi)

Python (re) code

pyPython
import re

pattern = re.compile(r"[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}", re.IGNORECASE)
input_text = "SW1A 1AA"
for m in pattern.finditer(input_text):
    print(m.group(0))

Stdlib `re` module — no third-party dependency. Works on Python 3.6+.

How the pattern works

1–2 letters, 1 digit, optional letter/digit, optional space, 1 digit, 2 letters. Case-insensitive flag handles lower and mixed case input.

Examples

Input

SW1A 1AA

Matches

  • SW1A 1AA

Input

EC1V 9LB

Matches

  • EC1V 9LB

Input

B33 8TH

Matches

  • B33 8TH

Same pattern, other engines

← Back to UK Postcode overview (all engines)