Raymond Wong
Raymond Wong

Reputation: 77

Remove spaces before punctuation with RegEx

I have the following C# code:

var sentence = "As a result , he failed the test   .";
var pattern = new Regex();
var outcome = pattern.Replace(sentence, String.Empty);

What should I do to the RegEx to obtain the following output:

As a result, he failed the test.

Upvotes: 3

Views: 3099

Answers (2)

Kobi
Kobi

Reputation: 138137

If you want to white-list punctuation marks that generally don't appear in English after spaces, you can use:

\s+(?=[.,?!])
  • \s+ - all white space characters. You may want [ ]+ instead.
  • (?=[.,?!]) - lookahead. The next character should be ., ,, ?, or ! .

Working example: https://regex101.com/r/iJ5vM8/1

Upvotes: 7

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627469

You need to add a pattern to your code that will match spaces before punctuation:

var sentence = "As a result , he failed the test   .";
var pattern = new Regex(@"\s+(\p{P})");
var outcome = pattern.Replace(sentence, "$1");

Output:

enter image description here

Upvotes: 3

Related Questions