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.
- The pattern's
\bmetacharacter matches on word boundaries. - As the name suggests, passing in
RegexOptions.IgnoreCasefor 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