US Postal State Codes

cwest on 2003-01-25T05:31:15

So, I thought it would be fun to have a regex that checks for a valid State Postal Code. There are 57 codes for the US, so I wanted to write a program to produce the regex. Here's the program:

#!/usr/local/bin/perl use strict; use warnings;

my @states = qw[ AL AK AS AZ CA CO CT DE DC FM FL GA GU HI ID IL IN IA KS KY LA ME MH MD MA MN MS MO MT NE NV NH NJ NM NY NC ND MP OH OK OR PW PA PR RI SC SD TN TX UT VT VI VA WA WV WI WY ];

my %sets = (); my @sets = ();

foreach ( @states ) { my ($first, $last) = split //; push @{$sets{$first}}, $last unless exists $sets{$last} && grep { $first eq $_ } @{$sets{$last}}; }

foreach ( keys %sets ) { push @sets, sprintf '%s[%s]', $_, join( '', @{$sets{$_}} ); }

my $regex = join '|', map "\n\t$_", @sets;

print "qr/(${regex}\n)/x\n";



And the output:

qr/( A[LKSZ]| C[AOT]| D[EC]| F[ML]| G[AU]| H[I]| I[DLNA]| K[SY]| M[EHDANSOTP]| N[EVHJYCD]| O[HKR]| P[WAR]| R[I]| S[CD]| T[NX]| U[T]| V[TIA]| W[AVIY] )/x

Of course this is a nearly unmaintainable piece of junk, but it was really fun to build.

The Greatest Story Ever Told - "All The Hype That Money Can Bu" by Five Iron Frenzy

Posted from caseywest.com, comment here.