WickedW
WickedW

Reputation: 2591

Beginner RegEx Replace Performance Question

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, @"&amp", "&");
        newstr = Regex.Replace(newstr, @" ", " ");
        newstr = Regex.Replace(newstr, @"&nbsp", " ");
        return newstr;
}

Thank you, Matt

Upvotes: 1

Views: 828

Answers (2)

ase
ase

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

Gumbo
Gumbo

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

Related Questions