Lamps Lamps - 1 year ago 68
C# Question

Parse and extract parts of UK Post code

I am trying to seperate Uk post code into area, district, sector. For e.g

if I have a post code like B75 5TW

I want the output as

  1. B75 5TW

  2. B75 5

  3. B75

  4. B7

I tried this regex but doesn't work as expected.


var regex = new Regex(@"^([A-Z]{1,2})([0-9][0-9A-Z]?)\s*([0-9])([A-Z]{2})$");
var matches = regex.Match(postcode);

Output should be like below
matches.groups[0] - B75 5TW
matches.groups[1] - B75 5

Any help much appreciated. thanks.

Answer Source

For that to work you want to nest your groups like so