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
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.
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)
. 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("$","$$"));
}
}
See the C# demo .
The Regex.Escape(find)
is only necessary if you expect special regex metacharacters in the find
variable value.
The regex demo is available at regexstorm.net .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.