mickbt mickbt - 3 years ago 99
C# Question

how to add whitespace to separate merged words with punctuation mark if it is between and keep it with whitespace

I need add white space if my input string, looks like this:


to pass it to write in text document like this:

"hello, world" with white-space and keep the punctuation mark at the place.

In other words I need to add one white-space after punctuation mark, if next word is merged with the previous word punctuation marks. And I need it for all, comma, dot, exclamation mark and dash.

So I'm not sure, if I can use this:

string input = "hello,world,world,world";

string pattern = @",(\S)";
string substitution = @", ";

Regex regex = new Regex(pattern);
string result = regex.Replace(input, substitution);

but in result it cuts first character of word after punctuation mark:

hello, orld, orld, orld

and desired result should be:

"hello, world, world, world"

Answer Source

Use the Regex.Replace overload which gets a MatchEvaluator delegate:

string input = "hello!world.world-world";
var result = Regex.Replace(input, @"[\,\.\-\!]", (m) => m + " ");

// hello! world. world- world

For more about the MatchEvaluator see: How does MatchEvaluator in Regex.Replace work?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download