Replace Specific Words in C#

I’ve been working on a decent size project and I have been learning a lot of new things that I thought I’d share with you guys. This will go over how to replace specific words using Regex in C#. For example if your string contains “Let’s add this pizza because adding pizza is a fad,” if you use normal removal tools such as string.Replace(“add”, “”) it would make the string “Let’s this pizza because ing pizza is a.”

Obviously, we don’t want that to happen, so the best tool to use is boundary.

What is a Boundary?
There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.


In simple words, boundary allows you to set it so that you only replace the word that has the string you want. You can use something simple such as String.Replace(@”\badd\b”, “”).

Remember to place

using System.Text.RegularExpressions;

on the top of your class/form.

I came up with a nice little class to remove a specific word:

    public static class LetsDoThis
        public static string ReplaceWords(this string variable, string findit, string getridofit, bool findspecificword)
            string finding_the_text= findspecificword? string.Format(@"\b{0}\b", findit) : findit;
            return Regex.Replace(variable, finding_the_text, getridofit);

Leave a Reply