Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace consecutive characters with same single character

Tags:

c#

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 "something likeeeee tttthhiiissss" then my final output should be "something like this".

The string can contain special characters too including space.

Can you guys suggest some simple way for doing this.

like image 293
Sachin Shanbhag Avatar asked Oct 19 '10 18:10

Sachin Shanbhag


1 Answers

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.

like image 137
alexn Avatar answered Oct 21 '22 09:10

alexn