What is the most efficient way to detect if a string contains a number of consecutive duplicate characters in C#?

前端 未结 6 2006
旧时难觅i
旧时难觅i 2021-02-15 22:20

For example, a user entered \"I love this post!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\"

the consecutive duplicate exclamation mark \"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\" should b

6条回答
  •  無奈伤痛
    2021-02-15 23:22

    The following regular expression would detect repeating chars. You could up the number or limit this to specific characters to make it more robust.

            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();
             }
    

提交回复
热议问题