1

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

"hello,world"

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"
Community
  • 1
  • 1

1 Answers1

0

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?

Community
  • 1
  • 1
Gilad Green
  • 36,708
  • 7
  • 61
  • 95