[英]Replace exact matching words containing special characters
我遇到了如何僅搜索和替換完全匹配的字符串 。 但是,當有以@開頭的單詞時,它不起作用。 我的小提琴在這里https://dotnetfiddle.net/9kgW4h
string textToFind = string.Format(@"\b{0}\b", "@bob");
Console.WriteLine(Regex.Replace("@bob!", textToFind, "me"));// "@bob!" instead of "me!"
另外,除了我想做的以外,如果一個單詞以\\ @開頭,例如說\\ @myname,並且如果我嘗試查找並替換@myname,則不應執行替換。
我建議用明確的基於環顧四周的邊界替換開頭和結尾的詞邊界,這將需要在搜索詞(?<!\\S)
和(?!\\S)
兩端使用空格字符或字符串的開頭/結尾。 此外,您需要在替換模式中使用$$
來替換文字$
。
我建議:
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("$","$$"));
}
}
參見C#演示 。
僅當您希望find
變量值中包含特殊的正則表達式元字符時,才需要Regex.Escape(find)
。
regex演示可從regexstorm.net獲得 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.