【问题标题】:Replace word and remove extra spaces替换单词并删除多余的空格
【发布时间】:2018-11-21 17:33:11
【问题描述】:

我正在使用以下代码将 & 符号替换为“and”。我遇到的问题是,当我有多个与号并排时,我最终会在“和”之间出现两个空格(“-and--and-”而不是“-and-and-”)。有没有办法可以将底部的两个正则表达式替换组合成一个,同时只删除&符号之间的重复间距?

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var replacedWord = Regex.Replace("&&", @"\s*&\s*", " and ");
        var withoutSpaces = Regex.Replace(replacedWord, @"\s+and\s+", " and ");
        Console.WriteLine(withoutSpaces);
    }
}

【问题讨论】:

  • 为什么要用Regex 来完成String.Replace("&","and") 也能完成的事情?
  • 作为一个快速的解决方案,您可以使用字符串方法Trim()
  • \s*&\s* 将删除 & 周围的重复空格(“--&-”将变为“-and-”)
  • 如果&在一个单词中也会添加空格(“ab&c”会变成“ab-and-c”)
  • @WiktorStribiżew 谢谢,大多数情况下都可以,但是是否可以在 ands 后面留一个空格?例如“a&b”变成“a-and-b”。在您提供的那个中,它变成了“a-andb”。

标签: c# asp.net regex


【解决方案1】:

使用String 扩展方法进行重复,

public static string Repeat(this string s, int n) => new StringBuilder(s.Length * n).Insert(0, s, n).ToString();

您可以使用 Regex.Replace 的 lambda(委托)版本:

var withoutSpaces = Regex.Replace("a&&b", @"(\s*&\s*)+", m => " "+"and ".Repeat(m.Groups[1].Captures.Count));

【讨论】:

    【解决方案2】:
    string input = "some&very&&longa&&&string";
    string pattern = "&";
    string x = Regex.Replace(input, pattern, m =>(input[m.Index-1] == '&' ? "": "-") + "and-");
    

    【讨论】: