Reputation: 2591
I have this simple regex replace based routine, is there anyway to improve its performance (and maybe also its elegance?)
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, @"&", "&");
newstr = Regex.Replace(newstr, @" ", " ");
newstr = Regex.Replace(newstr, @" ", " ");
return newstr;
}
Thank you, Matt
Upvotes: 1
Views: 828
Reputation: 13471
Since you are using zero regex features maybe there is another way. It seems like C# has a Replace method for strings, use that instead, I imagine that there is a lot of extra power used when doing regex instead of a simple replace.
Upvotes: 3
Reputation: 655219
You can combine most of the expressions until you end up with only three:
public static string stripshrapnel(string str)
{
string newstr = str.Trim();
newstr = Regex.Replace(newstr, @"[-',""?#;:+%[\]*/\\\\]", "");
newstr = Regex.Replace(newstr, @"&?", "&");
newstr = Regex.Replace(newstr, @" ?", " ");
return newstr;
}
Upvotes: 9