Java Regex – UK Postcode 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 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);
	System.out.println(matcher.matches());
}

Output:

true
true
true
true

false
false

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

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.