代码之家  ›  专栏  ›  技术社区  ›  Joe Schmoe

在C中使用正则表达式从字符串中删除无效字符#

  •  0
  • Joe Schmoe  · 技术社区  · 7 年前

    我找到了几个关于这个主题的帖子,但是上面提到的解决方案在我的案例中不起作用。

    请考虑以下代码:

        static void Main(string[] args)
        {
            string rgs = "^[ -~]*(?:\r?\n[ -~]*)*$";
    
            string TestStrNoMatch = "One\tTwo\r\nThree Ö";
            string TestStrMatch = "OneTwo\r\nThree ";
    
            Regex rgx = new Regex(rgs);
    
            bool Match = rgx.IsMatch(TestStrNoMatch); // false
    
            Match = rgx.IsMatch(TestStrMatch); // true
    
            string result = Regex.Replace(TestStrNoMatch, rgs, "");
    
            // result is the same as TestStrNoMatch
        }
    

    预期结果是将删除\t和_,但这不会发生。结果值与teststrnomatch完全相同

    澄清 :我在示例中使用的regex只允许空格和(英文字母、数字和一些特殊字符)之间的字符,以及windows和unix格式的新行。我想把其他的东西都拿走。

    2 回复  |  直到 7 年前
        1
  •  1
  •   N.D.C.    7 年前

    要使regex.replace工作,regex需要与要删除的字符匹配。因为你的模式与任何东西都不匹配,所以什么都不会被替换。目前还不清楚具体要删除哪些内容,但以下是一个示例:

    模式 (\\t)|(Ö) 匹配制表符和字符,所以

        string sample = "ab\tcefÖ";
        string pattern = "(\\t)|(Ö)";
        string result = Regex.Replace(sample, pattern, "");
        System.Console.WriteLine("SAMPLE : " + sample);
        System.Console.WriteLine("RESULT : " + result);
    

    结果在

    SAMPLE: ab      cefÖ
    RESULT: abcef
    

    如果你解释一下你想要删除的内容,我可以给你一个更具代表性的regex模式。例如,要删除空格和~,以及制表符之间的所有字符,可以使用 [^ -~]|(\\t) .

        2
  •  0
  •   Swift    7 年前

    为什么不直接使用regex呢?在我看来可读性更好。

    string text = "abcdef";
    char[] invalidChars = { 'a', 'b', 'c' }; // Your invalid characters here
    
    if (text.IndexOfAny(invalidChars) != -1)
    {
        text = new String(text.Where(c => !invalidChars.Contains(c)).ToArray());
    }
    

    输出:“def”