代码之家  ›  专栏  ›  技术社区  ›  Abe Miessler

.NET中的regex令牌替换?

  •  1
  • Abe Miessler  · 技术社区  · 14 年前

    我不确定“token replace”是否是正确的短语,但下面是我要做的:

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

    例子:

    a   b   b 
    

    会变成

    a b b
    

    还有:

    a
    
    
    b
    
    
    c
    

    会变成:

    a
    
    b
    
    c
    

    这可以用.NET regex完成吗?

    5 回复  |  直到 14 年前
        1
  •  2
  •   Bennor McCarthy    14 年前

    如果要正确替换双新行和空格,则需要使用此选项:

    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
    
        2
  •  0
  •   Community paulsm4    7 年前

    对于子孙后代,我的解决方案来自 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
  •  0
  •   Reinderien    14 年前

    是的,可以。使用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
  •  0
  •   JaredPar    14 年前

    这在regex中是可能的,但在添加了多个选项后,它会得到一个但不受欢迎的结果。这是一个regex示例,它只处理空白和制表符。

    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
  •  0
  •   JohnB    14 年前
    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");