【问题标题】:Replace exact matching words containing special characters替换包含特殊字符的完全匹配词
【发布时间】:2017-01-16 06:03:55
【问题描述】:

我遇到了How to search and replace exact matching strings only。但是,当有以@开头的单词时,它不起作用。我的小提琴在这里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,它不应该进行替换。

【问题讨论】:

  • 本题与escaping无关,与词界有关。您是否打算仅在没有前面和后面没有字符字符时匹配textToFind?在string.Format 中尝试@"(?<!\w){0}(?!\w)" 正则表达式并用replace.Replace("$", "$$") 替换(如果您的替换字符串可能包含您想视为文字字符的$ 符号)。
  • 至于“红利”部分,还不是很清楚,但也许@"(?<!\w)(?<!(?<!\\)\\(?:\\\\)*){0}(?!\w)" 可以?
  • 我打算匹配确切的单词。因此,如果我找到“@bob”并尝试替换它应该只匹配“@bob”而不是“@bob.com”或\@bob。同样对于 \@bob 应该只匹配 \@bob

标签: c# regex


【解决方案1】:

我建议用明确的基于环视的边界替换开头和结尾的单词边界,这将需要在搜索词的两端使用空格字符或字符串的开头/结尾,(?<!\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# demo

Regex.Escape(find) 仅在您希望 find 变量值中包含特殊的正则表达式元字符时才需要。

正则表达式演示可在regexstorm.net 获得。

【讨论】:

  • 感谢您的回答。但是,在这种情况下,它会替换 @google.com,因为查找字符串是“@google”,它应该只匹配该字符串,而不是包含“@google”的任何其他单词。
  • 你的意思是(?&lt;![\w\\])@google(?!\w)
  • 差不多了,它不应该匹配“@google.com”。它应该只匹配“@google”而不匹配其他内容。因此,当 '@google' 后跟任何特殊字符时,它不起作用。
  • 那么,在这种情况下,单词边界是空格吗?然后你需要(?&lt;!\S)@google(?!\S)
  • 完美。这正是我想要的。非常感谢。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多