c# UK postcode splitting

To maintain consistency with user inputted data, i wrote this small method in order to normalise UK post codes into the standard format.

The logic is as follows:

  1. Convert all the letters to their uppercase variant.
  2. Strip out any character that isn’t letter or a number using regular expressions and remove all spaces from the string.
  3. Split the post code using the substring method. We call this method twice, so we can get the first and last segments of the post code and insert a space before the last 3 characters.

The code:

public string fixPostCode(string postCode)
        postCode = postCode.ToUpper(); //Convert all letters to upper case
        Regex r = new Regex("(?:[^a-z0-9 ]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
        postCode = r.Replace(postCode, String.Empty).Replace(" ", "");

        return  postCode.Substring(0, postCode.Length - 3) + 
			" " + postCode.Substring(postCode.Length - 3);

You will need to include the following namespace into your class:


Go ahead and test it. Try an input string of something like: “M£$£^%£$£££66£$%££££&A)£$££^£%$(^P” and see what happens ;). N.B: You should get, “M6 6AP” as output.