Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex checking repeat

Tags:

java

c#

regex

I am trying to check a text line using regex.

1,3,4,5,8,10,12,14,19,14

Here numbers are delimited with ',' and should be non-negetive and less than or equals to 20. And also any number should not be repeated. Here is my pattern.

^(?:(?:0[1-9]|[1-9]|1[0-9]|20),)*(?:0[1-9]|[1-9]|1[0-9]|20)$

But it cant check the repeat. How can I check it ?

like image 722
Barun Avatar asked Dec 26 '12 20:12

Barun


1 Answers

What you want to do is not that complicated. You just need to check after each matched number if this number occurs once more in the string:

^(?:(0[1-9]|[1-9]|1[0-9]|20),(?!.*\b\1\b))*(?:0[1-9]|[1-9]|1[0-9]|20)$

See it and test it here on Regexr.

In C#:

string[] myStrings = { "1",
    "1,2",
    "01,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20",
    "01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20",
    "01,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,5",
    "01,02,03,04,05,06,07,08,13,09,10,11,12,13,14,15,16,17,18,19,20" };

Regex reg = new Regex(
    @"^
        (?:(0[1-9]|[1-9]|1[0-9]|20),
            (?!.*\b\1\b) # Fail if the before matched number occurs once more
        )*
        (?:0[1-9]|[1-9]|1[0-9]|20)
    $",
    RegexOptions.IgnorePatternWhitespace
);

foreach (string myString in myStrings)
    Console.WriteLine("{0} {1} a valid string.",
        myString,
        reg.IsMatch(myString) ? "is" : "is not"
    );

Console.ReadLine();
like image 104
stema Avatar answered Sep 18 '22 23:09

stema