leoOrion
leoOrion

Reputation: 1957

Dont match if values repeat in regex

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

Answers (1)

The fourth bird
The fourth bird

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]?\]

Regex demo

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]?\]

Regex demo

Upvotes: 2

Related Questions