0

I'm trying to create a regex matching the following patterns (with and without space):

M1 1AA, M60 1NW, CR2 6XH, DN55 1PT, W1A 1HQ and EC1A 1BB

I'm very new at this and find it hard to create a functional regex for all the examples above.

Searching here and there I found a regex that might work for some of the patterns but I don't know how to add the condition "with or without space" for each type of postcode.

Here the regex I found on another post "^(A-PR-UWYZ [0-9][ABD-HJLNP-UW-Z]{2})"

How do I add the space/no space condition? In order to match M11AA or M1 1AA.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
  • 1
    Some of us are not familiar with UK post codes. Can you give a few examples that should NOT match? Otherwise, it looks like any combination of capital letters and digits, starting with a capital letter, should match. – Chthonic Project Jul 22 '15 at 15:51
  • In the duplicate, in the accepted answer there are links to uk post codes syntax – Davide Lorenzo MARINO Jul 22 '15 at 15:53

1 Answers1

0

You need this regex:

^([A-PR-UWYZ](([0-9](([0-9]|[A-HJKSTUW])?)?)|([A-HK-Y][0-9]([0-9]|[ABEHMNPRVWXY])?)) ?[0-9][ABD-HJLNP-UW-Z]{2})$
                                                                                     ^

This space must be set as optional with ? quantifier that means 0 or 1 repetition.

See demo

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563