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
PASS
- E1 1EE
- E1
- AB9 4CD
>Solution :
Try:
([A-Z]+)\d+-\1\d+|(?!.*-)^.*$
([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 -