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..
-
What are the official rules on what part is what? What defines the split in the second example to be `AB11 1AD` instead of `AB1 11AD`? – Sean Jul 23 '09 at 14:24
-
1UK postcodes are either in the form 3 3 or 4 3 e.g. TS1 8TY or TS12 3TG – Lloyd Powell Jul 23 '09 at 14:31
-
It's a tricky one as user input could be anything and I'm trying to work around that when I perhaps shouldn't. There's only so far you can go. I'll possibly do something simple based on trying to split by a space if there is one, then using the length to guesstimate the correct place to split and then running thru the regex to check. Users - who needs em! – Tikeb Jul 23 '09 at 14:47
-
7@ThePower: Wrong, 2 3 is also valid (consider "W1" in London). – Richard Jul 23 '09 at 15:13
-
See http://stackoverflow.com/q/164979/20048 for postcode validation – Simon Feb 01 '12 at 11:31
12 Answers
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 lastDigitIndex = noSpaces.LastIndexOfAny(Digits);
if (lastDigitIndex == -1)
{
throw new ArgumentException("No digits!");
}
string normalized = noSpaces.Insert(lastDigitIndex, " ");
The Wikipedia entry has a lot of detail including regular expressions for validation (after normalisation :)
-
Yea this is excellent! I never thought of it that way round... The start has a few different formats, but the last 3 are always DIGIT ALPHA ALPHA! Genius in its simplicity! This is the correct answer! – Piotr Kula Aug 12 '15 at 14:54
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.

- 68,708
- 30
- 194
- 223
-
4That will fail if people put the space in the wrong place: "AB1 11AD". Wanna bet that won't happen? :) – Jon Skeet Jul 23 '09 at 14:53
-
3You're right, that would fail, but it would be just as easy to Replace any spaces before doing the Substring call. – Brandon Jul 23 '09 at 15:18
UK-postcodes format explained:
Ref: http://www.mrs.org.uk/pdf/postcodeformat.pdf
POSTCODE FORMAT
A Postcode is made up of the following elements:
PO1 3AX
- PO the area. There are 124 postcode areas in the UK
- 1 the district. There are approximately 20 Postcode districts in an area
- 3 the sector. There are approximately 3000 addresses in a sector.
- AX the Unit. There are approximately 15 addresses per unit.
The following list shows all valid Postcode formats. "A" indicates an alphabetic character and "N" indicates a numeric character.
FORMAT EXAMPLE:
AN NAA - M1 1AA
ANN NAA - M60 1NW
AAN NAA - CR2 6XH
AANN NAA - DN55 1PT
ANA NAA - W1A 1HQ
AANA NAA - EC1A 1BB
Please note the following:
- The letters Q, V and X are not used in the first position
- The letters I,J and Z are not used in the second position.
- The only letters to appear in the third position are A, B, C, D, E, F, G, H, J, K, S, T, U and W.
- The second half of the postcode is always consistent numeric, alpha, alpha format and the letters C, I, K, M, O and V are never used.
And it is safe to assume that the space
will be the forth character from the end, ie., if a postcode is missing a space, SW109RL
, you can blindly put a space at the 4th position from the end, SW10 9RL

- 7,016
- 5
- 54
- 92
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.

- 22,920
- 8
- 63
- 107
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
}

- 3,029
- 1
- 26
- 42
Assuming a valid input string, e.g. one that's passed the following regex:
"^[A-Za-z]{1,2}[0-9Rr][0-9A-Za-z]?\s*?[0-9][ABDEFGHJLNPQRSTUWXYZabdefghjlnpqrstuwxyz]{2}$"
Note: this allows optional space between the Outcode and Incode.
Then the following replacement regex will tidy it up - (splits it into two captures $1 and $2, then inserts the space):
postCode = Regex.Replace(postCode, "^(\S+?)\s*?(\d\w\w)$", "$1 $2")

- 2,982
- 2
- 20
- 25
I've written a method to handle this as best I can for my application.
Firstly I put a max length on my textbox @maxlength="8"
Then I call the following method in my controller:
if (searchString != null)
{
searchString = HtmlHelpers.ParseStringToUkPostcode(searchString);
}
The method consists of:
public static string ParseStringToUkPostcode(string inputPostcode)
{
string outputPostcode = inputPostcode;
outputPostcode = outputPostcode.Replace(" ", "").Trim();
string outward = outputPostcode.Substring(0, outputPostcode.Length - 3);
string inward = outputPostcode.Substring(Math.Max(0, outputPostcode.Length - 3));
string postcode = string.Format("{0} {1}", outward, inward);
outputPostcode = postcode;
return outputPostcode;
}
It's not pretty but it seems to be relatively robust for what I need and will handle the obvious variations of user provided post codes, in my area at least.
Disclaimer.
I don't need to look at postcodes outside my county as far as this app is concerned.

- 9,770
- 27
- 100
- 181
I wrote this regex based on @Jon Skeet's suggestion that last 3 are always digit-letter-letter
([a-zA-Z][a-zA-Z0-9]{1,3}) ?(\d[a-zA-Z]{2})
I will probably let through some bad ones due to this part [a-zA-Z0-9]{1,3}
but hey its good enough for me. You can test it here.

- 58,075
- 31
- 238
- 265
According to guidelines the UK Postcode's second part is always 3 characters starting with a number thus my excessive exception throwing. You can add other checks like; "if greater than 8 chars" and "if contains any numbers". Up to you.
Also please feel free to change the extension name, I don't like it, its too long. Happy coding!
Postcode Guide Guide to UK Postcodes
Try the following code:
Add it as a string extension so the use becomes easy.
Use this link to do that Create String Extensions
public static string FirstPartOfPostcode(this string str)
{
string postCodeNoSpaces = str.Replace(" ", "");
char lastDigit = postCodeNoSpaces[postCodeNoSpaces.Length - 3];
if(!Char.IsDigit(lastDigit))
{
throw new ArgumentException("Invalid PostCode");
}
string firstPart = postCodeNoSpaces.Substring(0, postCodeNoSpaces.Length - 3);
return firstPart;
}
Use:
string postcode = "AB111AD";
string firstPart = postcode.FirstPartOfPostcode();

- 79
- 1
- 7
Brandon is correct, you can substring on the last 3 characters because this is the format defined by the standard BS 7666. So "AA1 11AA" isn't in fact a valid postcode.
Apparently the only breach of BS 7666 is British Forces Post Office postcodes, which begin BFPO and end with 4 numbers, e.g. "BFPO 1234".
The Wikipedia entry has more information, as well as regexs for validation. It also has a choice quote: "completely accurate validation is only possible by attempting to deliver mail to the address."

- 157
- 6
Simply split the string in equally section or as your requirements it may be single/double/triple bit
string postCode = "AB111AD".Replace(" ", "");
string firstPart = postCode.Substring(0, postCode.Length - 3);
string lastPart = postCode.Substring(postCode.Length -3,postCode.Length);

- 2,389
- 23
- 39
-
1You just copied the accepted answer and formatted the whole thing as a code block. Can you explain what your answer adds to the existing ones, and format it properly? – CodeCaster Jun 16 '16 at 11:40
-
This answer is [guaranteed to not work](https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.8#System_String_Substring_System_Int32_System_Int32_) - it'll throw an ArgumentOutOfRangeException on the last line. – Wai Ha Lee Jan 06 '20 at 17:20
My PHP function for this problem ....
function ParseStringToUkPostcode($inputPostcode)
{
$outputPostcode = trim(str_replace(' ', '', $inputPostcode));
$firstPart = substr($outputPostcode, 0,strlen($outputPostcode)-3);
$lastPart = substr($outputPostcode,strlen($outputPostcode)-3);
$outputPostcode = $firstPart.' '.$lastPart;
return $outputPostcode;
}

- 99
- 5