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.