【问题标题】:Regex token replace in .NET?.NET 中的正则表达式令牌替换?
【发布时间】:2010-09-24 07:17:59
【问题描述】:

我不确定“令牌替换”是否是正确的短语,但这是我想要做的:

如果我在一个字符串中找到两个或多个连续的空格 (\s) 又名 - 空格、换行符、制表符等。我想用它自己的一个实例替换它匹配的任何内容。

例子:

a   b   b 

会变成

a b b

和:

a


b


c

会变成:

a

b

c

这可以使用 .net 正则表达式来完成吗?

【问题讨论】:

标签: .net regex


【解决方案1】:

如果您想正确替换双换行符和空格,则需要使用它:

string input = @"a


b


c  d  e";

string result = Regex.Replace(input, @"(\r\n|\s)\1", "$1");

\1 将查找与组 (\s|\r\n) 匹配的字符,替换字符串中的 $1 将仅用该组的单个实例替换匹配项。

如果您想用单个实例替换多个重复项(即连续 3 个),则需要使用 @"(\r\n|\s)\1+" 作为模式,但这样做的副作用是:

a


b


c

将减少为:

a
b
c

【讨论】:

  • +1:最后,很好的答案。捕获组然后再次使用它并处理 Windows 上烦人的\r\n
【解决方案2】:

为了后代,我的解决方案来自this question:

Regex 
    regex_select_all_multiple_whitespace_chars = 
        new Regex(@"\s+",RegexOptions.Compiled);

var cleanString=
    regex_select_all_multiple_whitespace_chars.Replace(dirtyString.Trim(), " ");

Regex 不是最好的方法。蛮力方法似乎要快得多。阅读上面的链接...

【讨论】:

  • 我认为你需要一个更长的变量名。
  • 该代码来自的类中的正则表达式声明的数量使该名称很有用。正则表达式非常不透明,因此我们选择通过显式描述性变量名称来消除一些不透明性。我通常会避免这种情况,但语言事物中的语言有时会使这种方法很方便。
【解决方案3】:

是的,它可以。使用 System.Text.RegularExpressions.Regex.Replace :

string str = "a   b   b";
Regex rexReplace = new Regex(" +");
str = rexReplace.Replace(str, new MatchEvaluator(delegate(Match match)
{
    return " ";
}));

【讨论】:

    【解决方案4】:

    这可以通过正则表达式实现,但在添加多个选项后会变得笨拙。这是仅处理空格和制表符的正则表达式示例。

    public static string ShrinkWhitespace(string input)
    {
        return Regex.Replace(input, @"(((?<t>\s)\s+)|((?<t>\t)\t+))", "${t}");
    }
    

    我发现如果将此类方法编码为简单方法,则更易于遵循和维护。例如。

    public string ShrinkWhitespace(string input) {
      var builder = new StringBuilder();
      var i = 0; 
      while ( i < input.Length ) {
        var current = input[i];
        builder.Append(current);
        switch ( current ) {
          case '\t':   
          case ' ': 
          case '\n': 
            i++;
            while ( i < input.Length && input[i] == current ) { 
              i++;
            }
            break;
          default:
            i++;
            break;
        }
      }
    
      return builder.ToString();
    }     
    

    【讨论】:

      【解决方案5】:
      string str = "a  b  c       a\r\n\r\nb\r\n\r\nc";
      
      string newstr = Regex.Replace(str, "(\u0200)+", " ");
      
      newstr = Regex.Replace(newstr, "(\t)+", "\t");
      
      newstr = Regex.Replace(newstr, "(\r\n)+", "\r\n");
      

      【讨论】:

      • 这不会用空格替换回车符。如果你看看我的例子,这不是我要找的。​​span>
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      相关资源
      最近更新 更多