Skip to main content
Perl

Validate UK Postcodes with Regular Expressions

By September 25, 2013No 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:

‘^[A-Z]{1,2}[0-9]{1,2}[A-Z]?s[0-9][A-Z][A-Z]$’

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

^[A-Z]

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.

^[A-Z]{1,2}

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

^[A-Z]{1,2}[0-9][1,2}

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

^[A-Z]{1,2}[0-9][1,2}[A-Z]?

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

^[A-Z]{1,2}[0-9][1,2}[A-Z]?s

s now requires a space

^[A-Z]{1,2}[0-9][1,2}[A-Z]?s[0-9][A-Z][A-Z]

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

^[A-Z]{1,2}[0-9][1,2}[A-Z]?s[0-9][A-Z][A-Z]$

Finally we assert the end of the record with the $

The final script would look similar to this:

#!/usr/bin/perl
print  "Enter a valid UK postode... ";
$pcode = <STDIN>;
chomp($pcode);
$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";
}