代码之家  ›  专栏  ›  技术社区  ›  user726720

Regex清理字符串

  •  -1
  • user726720  · 技术社区  · 7 年前

    我有以下字符串:

    Fox jumps over the rope (1):AB 123

    我想用C中的regex来清理这个。我需要它像:

    Fox jumps over the rope .

    我不能用regex匹配这个字符串

    string badstring = "Fox jumps over the rope (1):AB 123";
    string goodstring = Regex.Replace(strIn, @"[^\w\.@-]", "",
                                     RegexOptions.None, TimeSpan.FromSeconds(1.5));
    

    要删除的字符串应与括号内的数字和其后的所有文本匹配。

    4 回复  |  直到 7 年前
        1
  •  1
  •   Wiktor Stribiżew    7 年前

    您可以使用

    Regex.Replace(badstring, @"\s*\(\d+\).*", "")
    

    这个 \s*\(\d+\).* 正则表达式匹配

    • \s* -0+空白字符
    • \(\d+\) -A ( ,然后是1+位数字, )
    • .* -剩下的部分。

    这个 Regex.Replace 用空字符串替换所有不重叠的引用。

        2
  •  2
  •   Dmitrii Bychenko    7 年前

    如果要删除 后缀 ( "(1):AB 123" 在示例中)您可以尝试使用 林克 而不是 正则表达式 :借助 TakeWhile 在后缀出现之前,我们将获取所有必需的字符。

      using System.Linq;
    
      ...
    
      string raw = "Fox jumps over the rope (1):AB 123";
    
      // "Fox jumps over the rope "
      string cleared = string.Concat(raw
        .TakeWhile(c => char.IsLetter(c) || char.IsWhiteSpace(c)));
    
        3
  •  0
  •   lagripe    7 年前
        String Pattern = "[^a-zA-Z\\s]+[a-zA-Z]*";
        String StringToClean = "Fox jumps over (1):AB 123 the rope (1):AB 123";
        String StringCleaned = Regex.Replace(StringToClean, @Pattern, "");
        String Cleaned = Regex.Replace(StringCleaned, @"[\s]+", " ");
        Console.WriteLine(Cleaned);
    

    结果=狐狸跳过绳子

    在测试 RegexStorm C检验: Snippet

        4
  •  0
  •   JohnyL    7 年前
    var s = "Fox jumps over the rope (1):AB 123";
    var x = s.Substring(0, s.IndexOf("(") - 1);
    // or: var x = s.Split(" (")[0];