2

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.

Intrepid
  • 2,781
  • 2
  • 29
  • 54
  • Hello, just wanted to check: you want the regex to match `LS28NG` or to split it up and match `LS2` and `8NG` separately? – e h Mar 11 '14 at 12:25
  • possible duplicate of [Javascript UK postcode regex](http://stackoverflow.com/questions/11081786/javascript-uk-postcode-regex) – Ken White Mar 11 '14 at 12:45

3 Answers3

2

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.

Michelle
  • 2,830
  • 26
  • 33
0

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.

e h
  • 8,435
  • 7
  • 40
  • 58
0

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)$
arco444
  • 22,002
  • 12
  • 63
  • 67