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

初学者正则表达式替换性能问题

  •  1
  • WickedW  · 技术社区  · 15 年前

    我有一个简单的基于regex替换的程序,有没有改善它的性能(也许还有它的优雅?)

    public static string stripshrapnel(string str)
    {
            string newstr = str.Trim();
            newstr = Regex.Replace(newstr, @"-", "");
            newstr = Regex.Replace(newstr, @"'", "");
            newstr = Regex.Replace(newstr, @",", "");
            newstr = Regex.Replace(newstr, @"""", "");
            newstr = Regex.Replace(newstr, @"\?", "");
            newstr = Regex.Replace(newstr, @"\#", "");
            newstr = Regex.Replace(newstr, @"\;", "");
            newstr = Regex.Replace(newstr, @"\:", "");
            //newstr = Regex.Replace(newstr, @"\(", "");
            //newstr = Regex.Replace(newstr, @"\)", "");
            newstr = Regex.Replace(newstr, @"\+", "");
            newstr = Regex.Replace(newstr, @"\%", "");
            newstr = Regex.Replace(newstr, @"\[", "");
            newstr = Regex.Replace(newstr, @"\]", "");
            newstr = Regex.Replace(newstr, @"\*", "");
            newstr = Regex.Replace(newstr, @"\/", "");
            newstr = Regex.Replace(newstr, @"\\", "");
            newstr = Regex.Replace(newstr, @"&", "&");
            newstr = Regex.Replace(newstr, @"&amp", "&");
            newstr = Regex.Replace(newstr, @" ", " ");
            newstr = Regex.Replace(newstr, @"&nbsp", " ");
            return newstr;
    }
    

    谢谢您, 马特

    2 回复  |  直到 15 年前
        1
  •  9
  •   Gumbo    15 年前

    您可以组合大多数表达式,直到最后只有三个表达式:

    public static string stripshrapnel(string str)
    {
            string newstr = str.Trim();
            newstr = Regex.Replace(newstr, @"[-',""?#;:+%[\]*/\\\\]", "");
            newstr = Regex.Replace(newstr, @"&?", "&");
            newstr = Regex.Replace(newstr, @" ?", " ");
            return newstr;
    }
    
        2
  •  3
  •   ase    15 年前

    既然您使用的是零regex特性,那么可能还有另一种方法。似乎C有一个 Replace 对于字符串,使用这个方法,我认为在执行regex时使用了大量的额外功能,而不是简单的替换。