c0rd c0rd - 1 year ago 67
C# Question

Count the number of contiguous equal characters

I need to validate Serial numbers and one of the rules is that there are up to 5 contiguous equal characters allowed.

Example valid:

012W212222123 // 4x the digit 2 contiguous

Example invalid:

012W764444443 // 6x the digit 4

So I tried to get the maximum number of contiguous characters without success

int maxCount = "012W764444443".GroupBy(x => x).Max().Count();

Answer Source

I suggest using a regex for a check to see if there are 5 or more consecutive digits:

Regex.IsMatch(input, @"^(?!.*([0-9])\1{4})")

If any characters are meant:

Regex.IsMatch(input, @"^(?!.*(.)\1{4})")

See the regex demo

The regex finds a match in a string that contains less than 5 identical consecutive digits (version with [0-9]) or any characters other than a newline (version with .).


  • ^ - start of string -(?!.*(.)\1{4}) - a negative lookahead that fails the match if the pattern is matched:
    • .* - any 0+ chars other than a newline
    • (.) - Group 1 capturing any char but a newline
    • \1{4} - exactly 4 consecutive occurrences of the same value stored inside Group 1 (where \1 is a backreference and the {4} is a range/bound/limiting quantifier).


var strs = new List<string> { "012W212222123", "012W764444443"};
    foreach (var s in strs)
        Console.WriteLine("{0}: {1}", s, Regex.IsMatch(s, @"^(?!.*(.)\1{4})"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download