in reply to UK postcode regex

This is the regex I use for checking UK postcodes. It is similar, but uses alternation instead...
# Check UK postcode format # Format is LD DLL, LLD DLL, LDD DLL, or LLDD DLL where L = letter, D += digit $postcode = uc($postcode); # Could be removed if you use the /i regex +switch if ($postcode !~ /^(([A-Z]\d|[A-Z][A-Z]\d|[A-Z]\d\d|[A-Z][A-Z]\d\d)\s( +\d|o)[A-Z][A-Z])$/i) { $error_msg .= "Invalid postcode for UK.<br /><br />\n"; }
The (\d|o) has the letter o to cater for an incorrect o instead of a zero. To actually change it to a zero would require a second line (using the substitution operator). I don't know of any way to make that change in the regex line while it is being parsed... UPDATE: Looks like there are a couple of ways to do it in one line, including changing an incorrect letter o to a zero. I stand corrected :)
_______
Code is untested unless explicitly stated
mlh2003

Replies are listed 'Best First'.
Re^2: UK postcode regex
by tweetiepooh (Hermit) on Jan 20, 2006 at 14:48 UTC
    An additional format not in you list is LLDL (WC1N).

    The two parts form the incode (which postoffice) and the outcode (street address). The outcode is always DLL. The incode can be LD, LDD, LLD, LLDD or LLDL.

    You can use ZZ99 9ZZ for an official "no postcode" and I think ZZ98 9ZZ also can be used for special purposes.