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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With