mickbt mickbt - 1 month ago 6
C# Question

How to do not allow whitespace before specific punctuation mark

First of all I allow to the string only several punctuation marks, for example only dot and comma. It is does not shown here because no needed, just to know.

So if my string is:

string str = "hello,world,,,hello,, world... world ,,,, world ...";


Then I do not allow to repeat this marks more the one time:

string filtr1 = Regex.Replace(str, @"(\.|,){1,}", m => m.Value.First().ToString());


Then if words are merged with punctuation mark between, I replace it with white-space and keep mark at its place:

string filtr2 = Regex.Replace(filtr1, @"[\,\.]", (m) => m + " ");


and also allow only one white-space between words:

string result = Regex.Replace(filtr2, @"\s+", " ");


So now my result look like this:

hello, world, hello, world. world , world .


But also I need here, if user type white-space before punctuation mark, "hello , world" how do not allow white-space before specific symbols dot and comma to get this result "hello, world" for whole processed string result should be like this:

hello, world, hello, world. world, world.

Answer

Normalize white-spaces first, then it will be easier to write the punctuation pattern:

string result = Regex.Replace(str, @"\s+", " ");
result = Regex.Replace(result, @" ?([.,]) ?(?:\1 ?)*", "$1 ");