Skip to main content

Validate UK Postcodes with Regular Expressions

By September 25, 2013September 12th, 2022No Comments

Often regular expressions can appear a little daunting but like most things when we approach them as a little elements they are easier to understand. We will use perl on Linux to evaluate the postcode entered by the user interactively.

The pattern that we search for is:


Of course it looks s little bit like alphabet soup but broken down it is easy. In the video we do the same as in this document breaking down the expression step by step:


Start of the record


Now we say that the record must start with a capitol letter. The square brackets denote a character class and the hyphen allows for a range. So we are saying A through to Z.


We add quantifiers now say that we need a minimum of one letter and a maximum of two


Now we require one or two letters followed by one or two numbers, matching SW11 and W1, etc


The question mark that is added now make the previous character optional allowing 0 or 1 upper case character , now matching W1A as well as PE99


s now requires a space


After the space we now require 3 characters a number followed by two upper case letters.


Finally we assert the end of the record with the $

The final script would look similar to this:

print  "Enter a valid UK postode... ";
$pcode = <STDIN>;
$pcode = uc $pcode;
$pattern = '^[A-Z]{1,2}[0-9]{1,2}[A-Z]?s[0-9][A-Z][A-Z]$';
if ($pcode =~ /$pattern/) {
 print "We can to deliver to: $pcode n";
} else {
 print "We cannot find the postcode $pcode n";