Replace consecutive characters with same single character

后端 未结 5 2592
执笔经年
执笔经年 2021-02-20 05:58

I was just wondering if there is a simple way of doing this. i.e. Replacing the occurrence of consecutive characters with the same character.

For eg: - if my string is \

5条回答
  •  庸人自扰
    2021-02-20 06:44

    This should do it:

    var regex = new Regex("(.)\\1+");
    var str = "something likeeeee!! tttthhiiissss";
    
    Console.WriteLine(regex.Replace(str, "$1")); // something like! this
    

    The regex will match any character (.) and \\1+ will match whatever was captured in the first group.

提交回复
热议问题