-2

I'm trying to write a regex function that will return the sector of a postcode.

The user could type the following postcodes:

  1. WA14 5
  2. WA12 5GJ

I need the regex just to return the sector of the postcode.

I've tried the following but it doesn't work:

^[a-zA-Z]+\d\d?[a-zA-Z]?\s*\d+

^(((([A-Z][A-Z]{0,1})[0-9][A-Z0-9]{0,1}) {0,}[0-9]))$

Thanks

WebDevB
  • 492
  • 2
  • 7
  • 25
  • 6
    Assume many of us are not familiar with UK postal codes. That said, what is the output you are trying to get, i.e., what identifies the sector? – CB_Ron Aug 10 '20 at 23:30

2 Answers2

0

I'm not a PHP expert by any means (okay, I don't know anything about it). But this regex will return the value you want in the first capture group.

^[A-Za-z]{1,2}[\d]{1,2}\s(\d).*$

From a (brief) reading of the PHP docs, this should return the value you are looking for.

preg_match('/^[A-Za-z]{1,2}[\d]{1,2}\s(\d).*$/', 'WA12 5GJ', $match); // $match[1] is '5'

CB_Ron
  • 589
  • 4
  • 13
0

I deal with this in some detail in my Programmers guide to UK postcodes.

Firstly, the postcode sector in WebDevB's example is:

WA14 5

This graphic shows the format of a UK postcode:

Format of a UK postcode

The regular expression to match the sector is:

^[A-Z][A-Z]{0,1}[0-9][A-Z0-9]{0,1} [0-9]

You would use this in PHP like this:

$postcode = 'WA12 5BB';

preg_match('/^[A-Z][A-Z]{0,1}[0-9][A-Z0-9]{0,1} [0-9]/', $postcode, $matches);

print_r($matches);

This would output:

Array
(
    [0] => WA12 5
)

The output would be the same whether $postcode was WA12 5BB or WA12 5.

Dan Winchester
  • 324
  • 1
  • 7