How to replace a word in a string in C#

Published on

Last Updated on

Estimated Reading Time: 1 min

Problem

Sometimes you want to replace whole words from a string in C#. But string.Replace in C# replaces partial matches.

For example,

Let's assume that the string is "Test testing test tester", and we want to replace the word test with text.

If we use string.Replace, our resultant string would be "text texting text texter", but what we want is "text testing text tester"

Solution

You can use Regex.Replace to replace a whole word.

private static string ReplaceWholeWord(string input, string wordToReplace, string replacementWord)
{
    var pattern = $"\\b{wordToReplace}\\b";
    return Regex.Replace(input, pattern, replacementWord, RegexOptions.IgnoreCase);
}

There are a few things to note here.

  1. The pattern's \b metacharacter matches on word boundaries.
  2. As the name suggests, passing in RegexOptions.IgnoreCase for the options makes it case-insensitive.

Now we can use it like

var replacedString = ReplaceWholeWord("Test testing test tester", "test", "text");

References

Thanks

Thanks Avery Stephen for pointing out a typo in the original post