[英]C# Replace exact part of string containing special characters
我正在尝试使用以下代码替换字符串的一部分:
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);
}
但是,当我在字符串中包含特殊字符时,此操作将无效。 我尝试转义角色,但没有运气...
这是一个示例,我有以下字符串:
Peter[='111222'] + APeter[='111222']
我想用@
替换Peter[='111222']
,所以结果应该是: @ + APeter[='111222']
。 使用给定的代码,字符串保持原样,并且没有任何变化。
请注意,我可能会Steven.intr[A:B;>1], Sssdf.len, asd.ind
许多其他特殊字符(例如Steven.intr[A:B;>1], Sssdf.len, asd.ind
等)的情况,因此在我的情况下,我需要找到具有不同格式的完全匹配项。
提前致谢!
除了匹配单词边界以外,还匹配空格和/或字符串的开头/结尾。 这将适用于非字母数字。
同样,您需要转义字符串,并从替换中删除单词边界(在我的情况下为空格和/或行的开头/结尾):您可以使用lookahead / behindhind来做到这一点。
所以这一切都说:
public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord)
{
string textToFind = matchWholeWord ? string.Format(@"(?<=^|\s){0}(?=$|\s)", Regex.Escape(find)) : Regex.Escape(find);
return Regex.Replace(input, textToFind, replace);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.