Regular expressions for UK postcodes

UK postcodes are split into incodes and outcodes. The incode is the second part and the outcode is the first. In fact the structure is somewhat more complex than that, but the explanation is good enough for this recipe.

There are separate regular expressions for the incode and the outcode and one that tests both together. The allowable characters is actually more restricted than these expressions allow so they give false positives, but only one false negative.

GIR 0AA is also a valid postcode that does not follow the pattern described in these regular expressions. It is the postcode for Girobank. Whether it is relevant in your application only you know.

See also

By Kirit with contributions by nobody yet.
Libraries: Boost.Regex

Recipe source code

/*
    Post codes regexs
*/

#include <boost/regex.hpp>

const boost::regex c_postcode_outcode( "[A-Z]{1,2}[0-9][0-9A-Z]?" );
const boost::regex c_postcode_incode( "[0-9][A-Z]{2}" );
const boost::regex c_postcode( c_postcode_outcode.str() + " " + c_postcode_incode.str() );
const boost::regex c_postcode_with_girobank( "(GIR 0AA)|(" + c_postcode.str() + ")" );

/*
    Example use
*/

#include <iostream>

void test( const boost::regex &regex, const std::string &code, bool expect_match ) {
    // Find if it matches
    bool match( boost::regex_match( code, regex ) );

    // Display stars if the answer is not what we expected
    if ( match != expect_match )
        std::cout << "**** ";

    // Display answer
    std::cout << regex.str() << ( match ? " matched " : " did not match " ) << code << std::endl;
}

int main( ) {
    test( c_postcode_outcode, "BN1", true ); // Brighton
    test( c_postcode_outcode, "BR7", true ); // Bromley
    test( c_postcode_outcode, "WC2N", true ); // West end (north)
    test( c_postcode_outcode, "WC2", true ); // West end
    test( c_postcode_outcode, "B1", true ); // Birmingham
    test( c_postcode_outcode, "X", false );
    test( c_postcode_outcode, "GT", false );

    test( c_postcode_incode, "5LQ", true );
    test( c_postcode_incode, "GH", false );

    test( c_postcode, "BN7 9XX", true ); // Made up
    test( c_postcode, "BN 9XX", false );
    test( c_postcode, "BN7N 8TH", false ); // False positive
    test( c_postcode, "GIR 0AA", true ); // False negative

    test( c_postcode_with_girobank, "BN7 9XX", true ); // Made up
    test( c_postcode_with_girobank, "GIR 0AA", true ); // Girobank

    return 0;
}

This is not an official Boost site. For more information on Boost please see Boost.org.