簡體   English   中英

使用regex c#替換Exact匹配字符串

[英]Replace Exact matching string using regex c#

這是我的代碼片段:

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”。 我該如何解決?

你應該逃避文本:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM