Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Exact matching string using regex c#

Tags:

c#

regex

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?

like image 628
user3404700 Avatar asked Jan 29 '26 02:01

user3404700


1 Answers

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.

like image 132
xanatos Avatar answered Jan 30 '26 15:01

xanatos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!