user3404700
user3404700

Reputation: 33

Replace Exact matching string using regex c#

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

Answers (1)

xanatos
xanatos

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

Related Questions