mickbt mickbt - 1 month ago 7
C# Question

How to limit amount of specific symbol in the string when it repeats

how to limit amount of specific symbol in the string when it repeats for example, if I have an input: "Hello,,,, world....." to write it into the text document for example, I want to get it as "hello, world." remove all extra and keep only one symbol between words. Only for comma and dot, chars can be repeated.

Answer

You could do something like this:

var text = "Hello,,,, world.....";

var result = Regex.Replace(text, @"(\.|,){2,}", m => m.Value.First().ToString());

The regex @"(\.|,){2,}" will match . or , that occurs 2 or more times and replace the matched group for the first character in it.