Bhaskar
Bhaskar

Reputation: 1690

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.

^([A-Z]{1,2})([0-9][0-9A-Z]?)\s*([0-9])([A-Z]{2})$

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
    ...etc

Any help much appreciated. thanks.

Upvotes: 0

Views: 208

Answers (1)

juharr
juharr

Reputation: 32266

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

^((([A-Z]{1,2})[0-9][0-9A-Z]?)\s*[0-9])[A-Z]{2}$

Upvotes: 1

Related Questions