Is there an alternative to string.Replace that is case-insensitive?

Aheho picture Aheho · Oct 28, 2008 · Viewed 123.2k times · Source

I need to search a string and replace all occurrences of %FirstName% and %PolicyAmount% with a value pulled from a database. The problem is the capitalization of FirstName varies. That prevents me from using the String.Replace() method. I've seen web pages on the subject that suggest

Regex.Replace(strInput, strToken, strReplaceWith, RegexOptions.IgnoreCase);

However for some reason when I try and replace %PolicyAmount% with $0, the replacement never takes place. I assume that it has something to do with the dollar sign being a reserved character in regex.

Is there another method I can use that doesn't involve sanitizing the input to deal with regex special characters?

Answer

C. Dragon 76 picture C. Dragon 76 · Oct 28, 2008

Seems like string.Replace should have an overload that takes a StringComparison argument. Since it doesn't, you could try something like this:

public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison)
{
    StringBuilder sb = new StringBuilder();

    int previousIndex = 0;
    int index = str.IndexOf(oldValue, comparison);
    while (index != -1)
    {
        sb.Append(str.Substring(previousIndex, index - previousIndex));
        sb.Append(newValue);
        index += oldValue.Length;

        previousIndex = index;
        index = str.IndexOf(oldValue, index, comparison);
    }
    sb.Append(str.Substring(previousIndex));

    return sb.ToString();
}