[英]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.