Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex for postcode range

I have below postcode ranges that I need to match via a regex

PASS

  • E1-E9
  • E1-E1
  • E1-E99
  • A1-A999
  • AB5-AB77

FAIL

  • A1-B9
  • E1-EE9

The idea is to be able to take the above PASS ones and generate the "filling" codes, for example:
E1-E3 would generate E1, E2, E3. But first, I must validate it. Basically, the string parts need matching on both sides I think.

(Optional)

I need this regex only to apply if the range character is present "-". If this range character is not present, I need it to PASS, this would indicate it’s not a range postcode so it should not be validated as part of the original regex

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

PASS

  • E1 1EE
  • E1
  • AB9 4CD

>Solution :

Try:

([A-Z]+)\d+-\1\d+|(?!.*-)^.*$

Regex demo.


([A-Z]+) – capturing group, match one or more capital letters.
\d+- – match one or more digits and -
\1 – match the same letters as the first capturing group
\d+ – match one or more digits

OR:

(?!.*-)^.*$ – match the whole string if it doesn’t contain -

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading