Regex for UK Postal Code Validation

In this Java regex tutorial, we will Learn to use regular expressions to validate postal zip codes specific to UK. You can modify the regex to suit it for any other format as well.

1. What are valid UK postal codes

Postal codes in the U.K. (or postcodes) are composed of five to seven alphanumeric characters separated by a space. Those two parts are the outward code and the inward code.

The outward code includes the postcode area and the postcode district. The inward code includes the postcode sector and the postcode unit.

Examples of postcodes include “SW1W 0NY”, “PO16 7GZ”, “GU16 7HF”, or “L1 8JQ”.

The rules covering which characters can appear at particular positions are a little complicated and filled with exception cases. The regular expression given here therefore sticks to the basic rules only.

Regex: ^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$

For checking the validation rules on UK postal codes, follow this wikipedia page.

2. UK Postcode Validation Example

List<String> zips = new ArrayList<String>();
//Valid ZIP codes
zips.add("SW1W 0NY");  
zips.add("PO16 7GZ");  
zips.add("GU16 7HF");  
zips.add("L1 8JQ");  
//Invalid ZIP codes
zips.add("Z1A 0B1");
zips.add("A1A 0B11");
String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
Pattern pattern = Pattern.compile(regex);
for (String zip : zips)
  Matcher matcher = pattern.matcher(zip);

The program output:


Feel free to drop your questions related to above UK postcode validation example.

Happy Learning !!


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.