1

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.

Community
  • 1
  • 1
Frenz
  • 547
  • 1
  • 9
  • 21
  • 2
    This question has nothing to do with [escaping](http://stackoverflow.com/questions/20505914/escape-special-character-in-regex), but with word boundaries. Did you intend to match a `textToFind` only when not preceded and not followed with a word char? Try `@"(? – Wiktor Stribiżew Jan 16 '17 at 07:19
  • 1
    As for the "bonus" part, it is not quite clear, but perhaps, `@"(? – Wiktor Stribiżew Jan 16 '17 at 07:57
  • I intent to match exact words. So if I find '@bob' and try to replace it should match only '@bob' and not '@bob.com' or \@bob. Similarly for \@bob should match only \@bob – Frenz Jan 16 '17 at 23:01

1 Answers1

3

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.

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476