使用 RegEx 删除标点符号前的空格

问题描述 投票:0回答:2

我有以下 C# 代码:

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

我应该对正则表达式做什么才能获得以下输出:

结果他没通过考试。

c# regex
2个回答
7
投票

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

\s+(?=[.,?!])
  • \s+
    - 所有空白字符。您可能需要
    [ ]+
  • (?=[.,?!])
    - 前瞻。下一个字符应该是
    .
    ,
    ?
    !
    .

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


3
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.