Intrepid
Intrepid

Reputation: 2831

Regex for UK postcode

I have this regex that I want to use to parse a UK postcode, but it doesn't work when a postcode is entered without spaces.

^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?) {1,2}([0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$

What change(s) do I need to make to this regex so it'll work without spaces correctly?

If I supply LS28NG I would expect the regex to return two matches for LS2 and 8NG.

Upvotes: 2

Views: 227

Answers (3)

Michelle
Michelle

Reputation: 2900

This worked for me, at least for your example of LS28NG:

^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?) {0,2}([0-9][ABD-HJLN-UW-Z]{2}|GIR ?0AA)$

I changed the repetitions after the space to 0-2 instead of 1-2, and made the space in GIR 0AA optional.

Upvotes: 2

arco444
arco444

Reputation: 22881

Just add an optional space \s? at the end of the first group:

^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?\s?){1,2}([0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$

Upvotes: 0

e h
e h

Reputation: 8913

Try adding \s{0,2} and putting brackets around the first and second part of the expression:

^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?)\s{0,2}([0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$

For:

LS2 8NG
LS28NG

It will match:

LS2 and 8NG
LS2 and 8NG

See it in action.

Upvotes: 0

Related Questions