Reputation: 33
Here is my code snippet:
public static class StringExtensions
{
public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord)
{
string textToFind = matchWholeWord ? string.Format(@"\b{0}\b", find) : find;
return Regex.Replace(input, textToFind, replace);
}
}
selectColumns = selectColumns.SafeReplace("RegistrantData.HomePhone","RegistrantData.HomePhoneAreaCode + '-' + RegistrantData.HomePhonePrefix + '-' + RegistrantData.HomePhoneSuffix", true);
However this also replaces the string "RegistrantData_HomePhone". How do i fix this?
Upvotes: 3
Views: 1237
Reputation: 111870
You should escape the text:
string textToFind = matchWholeWord ? string.Format(@"\b{0}\b", Regex.Escape(find)) : Regex.Escape(find);
Regex.Escape will replace (for example) .
(of RegistrantData**.**HomePhone)
with \.
(and many other sequences)
It could be a good idea to
return Regex.Replace(input, textToFind, replace.Replace("$", "$$"));
because the $
has a special meaning in Regex.Replace
(See Handling regex escape replacement text that contains the dollar character). Note that for replacement you can't use Regex.Escape
.
Upvotes: 3