3

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?

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.