views:

705

answers:

4

I need a way to split a UK postcode from user entry. This means the postocode could be nicely formatted full code like so "AB1 1BA" or it could be anything you could imagine. I've seen some regex to check the format of the postcode but it's knowing where to split it if I'm given something like "AB111AD" etc.. This is to return the first part of the postcode, in the example above would be "AB11". Any thoughts? Thanks..

+2  A: 

I've written something similar in the past. I think you can just split before the last digit. (e.g. remove all spaces, find the last digit and then insert a space before it):

static readonly char[] Digits = "0123456789".ToCharArray();

...

string noSpaces = original.Replace(" ", "");
int lastDigit = noSpaces.LastIndexOfAny(Digits);
if (lastDigit == -1)
{
    throw new ArgumentException("No digits!");
}
string normalized = noSpaces.Insert(lastDigit, " ");

The Wikipedia entry has a lot of detail including regular expressions for validation (after normalisation :)

Jon Skeet
+3  A: 

I'm not sure how UK Post Codes work, so is the last part considered the last 3 characters with the first part being everything before?

If it is, something like this should work, assuming you've already handled appropriate validation: (Edited thanks to Jon Skeets commment)

string postCode = "AB111AD".Replace(" ", "");
string firstPart = postCode.Substring(0, postCode.Length - 3);

That will return the Post Code minus the last 3 characters.

Brandon
That will fail if people put the space in the wrong place: "AB1 11AD". Wanna bet that won't happen? :)
Jon Skeet
You're right, that would fail, but it would be just as easy to Replace any spaces before doing the Substring call.
Brandon
If it can happen...it will
ThePower
A: 

I have worked with many UK insurance websites and we normally ask both the parts in different text boxes. How are you validating the address? In some sites we ask the post code together but we use QAS to validate the postcode and ask the user to select the address. QAS can validate even if the postcode is entered together.

Shoban
A: 

Regular expressions may help to easily parse UK post code by using named groups for each part of the code. Regular expressions may be taken from here:

http://www.regxlib.com/REDetails.aspx?regexp_id=260

or here:

http://www.mgbrown.com/PermaLink66.aspx



string ukPostCode = "AB1 1BA";
// Add group names in the pattern like this {FIRST_GROUP}    
string UK_POST_PATTERN = @"^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$";

Regex ukPostRegex = new Regex(UK_POST_PATTERN, RegexOptions.Compiled);

Match match = ukPostRegex.Match(ukPostCode);
if (match.Success)
{
    Group group = match.Groups["FIRST_GROUP"];
   // etc
}

Boris Modylevsky