ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Matching Royal Mail Postal Codes
Submitter: Ken Simpson (other recipes)
Last Updated: 2001/06/20
Version no: 1.0
Category: Miscellaneous

 

4 stars 1 vote(s)


Approved

Description:

This regular expression matches valid postal codes as defined by the Royal Mail
(the UK's postal company).

Usage: Text Source

#!/usr/bin/perl -w
# postcode - validate British post codes (demo for clpm)
# Craig Berry (20010614)

use strict;

my @patterns = ('AN NAA', 'ANN NAA', 'AAN NAA', 'AANN NAA',
                'ANA NAA', 'AANA NAA', 'AAA NAA');

foreach (@patterns) {
  s/A/[A-Z]/g;
  s/N/\\d/g;
  s/ /\\s?/g;
}

my $re = join '|', @patterns;

while (<>) {
  print /^(?:$re)$/o ? "valid\n" : "invalid\n";
}

The license for this recipe is available here.

Discussion:

This regular expression comes to us from Craig Berry from a posting
in the comp.lang.perl.misc newsgroup (article 30293132).
The regular expression is built by grokking the @patterns array, replacing A's
with [A-Z], N's with \d, and spaces with \s? and combining the elements of
the array with branch operators (i.e., the pipe character, '|').



Add comment

Number of comments: 1

Not quite complete, Maurice Hickey, 2002/03/09
The UK postcode is broken down into 2 parts, the outward (first) and inward (second) parts. I believe that the postoffice define that to be valid, the inward part cannot contain any of the the characters CIKMOV
Add comment



Highest rated recipes:

1. Breaking down a URI into ...

2. Finding Palindromes

3. Extracting HTML URL Links

4. Removing dangerous ...

5. Matching Royal Mail ...

6. Finding URLs in text -- ...

7. Validating email ...

8. Validate Domain Names

9. Extract the Korean ...

10. Remove any HTML




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.