Skip to main content
 首页 » 编程设计

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

2024年01月13日36qq号

我有这个简单的基于正则表达式替换的例程,有没有办法提高它的性能(也许还有它的优雅?)

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; 
} 

谢谢, 马特

请您参考如下方法:

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

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