Search code examples
c#regexregex-lookaroundsregex-greedy

Regex to avoid data duplication in delimited string?


I am trying to validate the data which will be string value with the , delimited. What I want is to validate that there should not be repetition of the same value within the sting.

Ex. my value would be.

    data1 = "value1,value2,value3,va-lu4,value 6,value1";//should fail
    data2 = "value1,value2,value3,va-lu4,value 6";//should pass

In above scenario data1 should fail as it contains the value1 twice. And in data2 should pass or match as it doesnot contain any repeated value.

This is what I got for matching the each value but not sure how to check for the repetition.

    ^[-\w\s]+(?:,[-\w\s]*)*$

This will matches the values between delimiter but not sure how to check if duplicate values exist. Any help would be great.
Note- I know I can do this using the sting functions and loop bu I was learning the Regex and want to try if it is possible using the regex.In case of confusion feel free to comment AS this is my first question on Stack.


Solution

  • ^(?!(?:^|.*,)([^,\n]*),.*\1(?:,|$)).*$
    

    Try this.See demo.

    https://regex101.com/r/wU7sQ0/24