使用RegEx删除非单词字符前的空格

时间:2015-04-21 07:35:14

标签: c# regex

我有以下C#代码:

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

我应该如何处理RegEx以获得以下输出:

  

结果,他没能通过测试。

2 个答案:

答案 0 :(得分:5)

如果您想列出通常在空格后不会出现在英文中的标点符号,您可以使用:

\s+(?=[.,?!])
  • \s+ - 所有空格字符。您可能需要[ ]+代替。
  • (?=[.,?!]) - 向前看。下一个字符应为.,?!

工作示例:https://regex101.com/r/iJ5vM8/1

答案 1 :(得分:2)

您需要在代码中添加一个模式,以便在标点符号之前匹配空格:

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

输出:

enter image description here