Written on 27 March 2014
Postcode Grouping Regular Expression for Royal Mail Line Listing Reports
There are many regex postcode validators out there, some good, some not so great, but few cover splitting the postcode into it’s 4 elements in order to use and process this data.
In my case I have created this regular expression to develop an in-house sorting office for Royal Mail’s line listing reports.
The following regex breaks the Postcode into 4 sections:
([A-Z]{1,2})([0-9]{1,2}[A-Z]?)[ ]?([0-9])([A-Z]{2})
A full London postcode can comprise of the following :
A-Alpha N-Numeric
AANNA NAA
AA (1 or 2 letters), NN (1 or 2 digits), A (0 or 1 letter – used for some London postcodes), Optional Space, N (1 digit), AA (2 letters) To obtain useful data from the postcode it has to be split into the following 4 groups:
From here the data can be used to lookup the relevant sorting areas in the UK, and perform either a low or high level sort and line listing report for Royal Mail. Here is an example of a C# function using a regex to split out both part entered and fully entered postcodes. Different types of sort can be performed if only a partial match is available, so this function is helpful when trying to sort through as much data as possible.
public class RegexUtilities
{
public static PostCodeElements PostCodeSplit(string postcode)
{
Match mc = Regex.Match(postcode, "([A-Z]{1,2})([0-9]{1,2}[A-Z]?)[ ]?([0-9])([A-Z]{2})", RegexOptions.IgnoreCase);
// Partial match is not supported with the above expression
if (mc.Groups.Count == 5)
return new PostCodeElements() { section1 = mc.Groups[1].Value, section2 = mc.Groups[2].Value, section3 = Convert.ToInt32(mc.Groups[3].Value), section4 = mc.Groups[4].Value };
// Attempt a partial match AA NN N
mc = Regex.Match(postcode, "([A-Z]{1,2})([0-9]{1,2})[ ]?([0-9])", RegexOptions.IgnoreCase);
if (mc.Groups.Count == 4)
return new PostCodeElements() { section1 = mc.Groups[1].Value, section2 = mc.Groups[2].Value, section3 = Convert.ToInt32(mc.Groups[3].Value), section4 = null };
// Attempt a partial match AA NN
mc = Regex.Match(postcode, "([A-Z]{1,2})([0-9]{1,2})[ ]?([0-9])", RegexOptions.IgnoreCase);
if (mc.Groups.Count == 3)
return new PostCodeElements() { section1 = mc.Groups[1].Value, section2 = mc.Groups[2].Value, section3 = null, section4 = null };
return null;
}
}