【问题标题】:Replace two or more spaces with Regex in C#在 C# 中用正则表达式替换两个或多个空格
【发布时间】:2011-07-02 08:10:36
【问题描述】:

我对正则表达式的东西很害怕。我想在 C# 中使用正则表达式将任意两个或多个空格转换为不间断空格。我想单独留下一个空格。

Sample     Sample

会产生

Sample     Sample

但是

Sample Sample

不会受到影响。

有什么想法吗?

提前致谢。

【问题讨论】:

    标签: c# asp.net html regex


    【解决方案1】:

    您可以使用MatchEvaluator 作为替换参数。在 C# 3.0 或更高版本中,您可以使用 lambda 函数:

    s = Regex.Replace(s, " {2,}", x => x.Value.Replace(" ", " "));
    

    【讨论】:

    • 谢谢。我想这会很简单。我只是很难处理这些东西。
    【解决方案2】:

    它基于零宽度正向前瞻和后向断言。

    MSDN

    var rx = new Regex(" (?= )|(?<= ) ");
    
    var str = "ab   cde f";
    var res = rx.Replace(str, "&nbsp;");
    
    // res == ab&nbsp;&nbsp;&nbsp;cde f
    

    【讨论】:

    • @Mark 相反,我想以“简单”的方式使用它,但我忘记了使用 MatchEvaluator 函数:-)
    猜你喜欢
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2021-02-01
    • 2021-07-04
    • 2015-02-21
    相关资源
    最近更新 更多