使用正则表达式在C#中替换精确匹配的字符串

3
这是我的代码片段:
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);

然而,这也替换了字符串“RegistrantData_HomePhone”。我该如何修复?
1个回答

3

您应该对文本进行转义:

string textToFind = matchWholeWord ? string.Format(@"\b{0}\b", Regex.Escape(find)) : Regex.Escape(find);

Regex.Escape 方法可以将 (例如) RegistrantData**.**HomePhone 中的 . 替换为 \.(以及其他许多序列)。

这可能是个好主意。

return Regex.Replace(input, textToFind, replace.Replace("$", "$$"));

因为在Regex.Replace中,美元符号$具有特殊的含义(请参见处理包含美元符号的正则表达式转义替换文本)。请注意,在替换过程中,您不能使用Regex.Escape

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接