'Regex validation of two patterns multiple comma-separated doesn't work
In an ASP.NET form I am trying to find a pattern allowing multiple comma-separated elements but it doesn't seem to work. I need to allow either 4 letters and 2 digits (JEAN01) or 2 digits and 4 letters (01JEAN) any number of times: JEAN01,JEAN02,03JEAN,JEAN04
My first attempt (see https://regex101.com/r/E4JZVv/1) is:
/^([a-z-A-Z]{4}[0-9]{2}|[a-z-A-Z]{2}[0-9]{4})(,[a-z-A-Z]{4}[0-9]{2}|[a-z-A-Z]{2}[0-9]{4})*$
My second attempt (https://regex101.com/r/HU9cOS/1) is
((^|[,])[a-z-A-Z]{4}[0-9]{2}|[a-z-A-Z]{2}[0-9]{4})+
The first accepts only a couple of elements.
Solution 1:[1]
The setup of your first try is good, only:
- you want to match
4 letters and 2 digits or 2 digits and 4 letterswhich is different from this part[a-z-A-Z]{2}[0-9]{4} - In the repetition of the group in the second part, you have to repeat the comma and put that following alternation itself also in a group so that the comma can be prepended for both alternations
Using a case insensitive match:
(?i)^(?:[a-z]{4}[0-9]{2}|[0-9]{2}[a-z]{4})(?:,(?:[a-z]{4}[0-9]{2}|[0-9]{2}[a-z]{4}))*$
See a regex demo.
For the second pattern that you tried, the assertion for the start of the string should not be in an alternation, or else you can have partial matches as it will also allow a comma.
You can repeat the alternation with an optional comma at the end. If you don't want to allow the string to start with a comma, you can for example using a negative lookahead (?!,) and use the alternation after asserting the start of the string.
(?i)^(?!,)((?:,|^)(?:[a-z]{4}[0-9]{2}|[0-9]{2}[a-z]{4}))+$
See another regex demo.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
