# Regular Expression Solutions to Common Problems

• Print
This chapter is from the book

## United Kingdom Postcodes

United Kingdom postcodes are five, six, or seven characters and digits defined by the Royal Mail. Postcodes are made up of two parts: the outward postcode (or outcode) and the inward postcode (or incode). The outcode is one or two alphabetic characters followed by one or two digits, or one or two characters followed by a digit and a character. The incode is always a single digit followed by two characters (any characters excluding C, I, K, M, O, and V, which are never used in postcodes). The incode and outcode are separated by a space.

```171 Kyverdale Road, London N16 6PS
33 Main Street, Portsmouth, P01 3AX
18 High Street, London NW11 8AB```
`[A-Z]{ 1,2} \ d[A-Z\ d]? \ d[ABD-HJLNP-UW-Z]{ 2}`
```171 Kyverdale Road, London N16 6PS
33 Main Street, Portsmouth, P01 3AX
18 High Street, London NW11 8AB```

The incode first matches one or two alphabetic characters followed by a digit using [A-Z]{ 1,2} \ d. [A-Z\ d]? matches an additional alphanumeric character if it exists. As such, [A-Z]{ 1,2} \ d[A-Z\ d]? matches every possible valid incode combination. To match the outcode, the pattern \ d[ABD-HJLNP-UW-Z]{ 2} is used; this matches a single digit followed by two of the allowed alphabetic characters (A, B, D through H, J, L, N, P through U, and W through Z).