Search code examples
c#.netstring.net-2.0replace

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


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?


Solution

  • From MSDN
    $0 - "Substitutes the last substring matched by group number number (decimal)."

    In .NET Regular expressions group 0 is always the entire match. For a literal $ you need to

    string value = Regex.Replace("%PolicyAmount%", "%PolicyAmount%", @"$$0", RegexOptions.IgnoreCase);