views:

4907

answers:

7

I need to search a string and replace all occurances 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?

A: 
Regex.Replace(strInput, strToken.Replace("$", "[$]"), strReplaceWith, RegexOptions.IgnoreCase);
Joel Coehoorn
This doesn't work. The $ is not in the token. It's in the strReplace With string.
Aheho
And you can't adapt it for that?
Joel Coehoorn
This site is supposed to be a repository for correct answers. Not answers that are almost correct.
Aheho
Talk about gift horses... a base level of ability to adapt may be assumed I feel.
annakata
A: 

The regular expression method should work. However what you can also do is lower case the string from the database, lower case the %variables% you have, and then locate the positions and lengths in the lower cased string from the database. Remember, positions in a string don't change just because its lower cased.

Then using a loop that goes in reverse (its easier, if you do not you will have to keep a running count of where later points move to) remove from your non-lower cased string from the database the %variables% by their position and length and insert the replacement values.

cfeduke
By reverse, I mean process the found locations in reverse from furthest to shortest, not traverse the string from the database in reverse.
cfeduke
You could, or you could just use the Regex :)
Ray
+6  A: 

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);
Todd White
+10  A: 

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

static public 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();
}
C. Dragon 76
I like this alot...
CraftyFella
Extension methods only work in 3+ right? +1 All the same, since the OP wasn't specific, but you may want to mention it
Chad Ruppert
Also, this will be faster than the regex.
John Gietzen
Nice. I would change `ReplaceString` to `Replace`.
AMissico
A: 

Another interesting post on this can be found on Rick Strahl's Blog:

http://www.west-wind.com/weblog/posts/60355.aspx

CraftyFella
A: 

Here is my post link that might help you

http://patelshailesh.com/index.php/case-insensitive-string-replace

shailesh
A: 

Seems the easiest method is simply to use the Replace method that ships with .Net and has been around since .Net 1.0:

string res = Microsoft.VisualBasic.Strings.Replace(res, 
                                   "%PolicyAmount%", 
                                   "$0", 
                                   Compare: CompareMethod.Text);
Clever Human