繁体   English   中英

替换包含特殊字符的完全匹配词

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM