我试图用以下代码替换字符串的一部分:
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等,因此,在我的情况下,我需要找到与不同格式的精确匹配。
提前感谢!
发布于 2016-07-05 10:24:57
不要匹配单词边界,而要匹配空格和/或乞讨/结束字符串。这将适用于非字母数字。
另外,您需要转义字符串,并从替换中移除单词边界(在我的例子中,是空格和/或开始/结束):您可以使用展望/查找。
所以这一切都说:
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);
} https://stackoverflow.com/questions/38199689
复制相似问题