[英]Replace exact matching words containing special characters
I came across How to search and replace exact matching strings only . 我遇到了如何仅搜索和替换完全匹配的字符串 。 However, it doesn't work when there are words that start with @. 但是,当有以@开头的单词时,它不起作用。 My fiddle here https://dotnetfiddle.net/9kgW4h 我的小提琴在这里https://dotnetfiddle.net/9kgW4h
string textToFind = string.Format(@"\b{0}\b", "@bob");
Console.WriteLine(Regex.Replace("@bob!", textToFind, "me"));// "@bob!" instead of "me!"
Also, in addition to that what I would like to do is that, if a word starts with \\@ say for example \\@myname and if I try to find and replace @myname, it shouldn't do the replace. 另外,除了我想做的以外,如果一个单词以\\ @开头,例如说\\ @myname,并且如果我尝试查找并替换@myname,则不应执行替换。
I suggest replacing the leading and trailing word boundaries with unambiguous lookaround-based boundaries that will require whitespace chars or start/end of string on both ends of the search word, (?<!\\S)
and (?!\\S)
. 我建议用明确的基于环顾四周的边界替换开头和结尾的词边界,这将需要在搜索词(?<!\\S)
和(?!\\S)
两端使用空格字符或字符串的开头/结尾。 Besides, you need to use $$
in the replacement pattern to replace with a literal $
. 此外,您需要在替换模式中使用$$
来替换文字$
。
I suggest: 我建议:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string text = @"It is @google.com or @google w@google \@google \\@google";
string result = SafeReplace(text,"@google", "some domain", true);
Console.WriteLine(result);
}
public static string SafeReplace(string input, string find, string replace, bool matchWholeWord)
{
string textToFind = matchWholeWord ? string.Format(@"(?<!\S){0}(?!\S)", Regex.Escape(find)) : find;
return Regex.Replace(input, textToFind, replace.Replace("$","$$"));
}
}
The Regex.Escape(find)
is only necessary if you expect special regex metacharacters in the find
variable value. 仅当您希望find
变量值中包含特殊的正则表达式元字符时,才需要Regex.Escape(find)
。
The regex demo is available at regexstorm.net . regex演示可从regexstorm.net获得 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.