检测字符串是否在C#中包含多个连续重复字符的最有效方法是什么?

sil*_*ent 8 c# string

例如,用户输入"我喜欢这篇文章!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"

连续的重复感叹号"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" 应该被发现.

Chi*_*omb 3

以下正则表达式将检测重复字符。您可以增加数量或将其限制为特定字符以使其更加强大。

        int threshold = 3;
        string stringToMatch = "thisstringrepeatsss";
        string pattern = "(\\d)\\" + threshold + " + ";
        Regex r = new Regex(pattern);
        Match m = r.Match(stringToMatch);
        while(m.Success)
        {
                Console.WriteLine("character passes threshold " + m.ToString());
                m = m.NextMatch();
         }
Run Code Online (Sandbox Code Playgroud)