初学者RegEx取代性能问题

时间:2009-11-08 11:15:23

标签: c# regex performance

我有这个简单的正则表达替换为基础的例程,无论如何都有提高它的性能(也许它的优雅?)

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 个答案:

答案 0 :(得分:9)

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

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

答案 1 :(得分:3)

由于您使用零正则表达式功能,可能还有另一种方法。看起来C#对字符串有一个Replace方法,而不是使用它,我想在使用正则表达式而不是简单替换时会有很多额外的功能。