Reputation: 1957
I want to match using this regex -
/\[([1-6],){0,5}[1-6]\]/
Some examples that should match are -
[1,2,3,4,5,6]
[2]
[1,2,3]
[1,2]
[1,2]
[1,4,2]
A string which is an array of numbers with max possible length as 6. The numbers can only be between 1 and 6. The regex works. But I dont want it to match something like this -
[1,2,3,2]
[1,2,2]
[2,2]
Basically the numbers shouldnt repeat. If they do, the regex should not match. How do I have to change the regex to achieve this?
Upvotes: 0
Views: 234
Reputation: 163632
As you are matching the exact pattern, you can assert using a negative lookahead with a capturing group and backreference (?!.*(\d).*\1)
that there is no occurrence of the same digit twice.
^(?!.*(\d).*\1)\[(?:[1-6],){0,5}[1-6]?\]
A slightly more optimized pattern could be matching only comma's and digits [,\d]*
instead of using .*
^\[(?![\d,]*(\d)[\d,]*\1)(?:[1-6],){0,5}[1-6]?\]
Upvotes: 2