This post will discuss how to replace all occurrences of a substring with another string in C#.

The Regex.Replace method replaces all matching occurrences of a substring with the specified replacement string. The pattern match is determined by a regular expression. It is available in the System.Text.RegularExpressions namespace and can be used either for removing all occurrences of a substring from a string or replacing all occurrences of a substring with another string.

1. Replace Substring

The following example demonstrates the usage of the Regex.Replace method by replacing all occurrences of a substring with another string.

Download  Run Code

2. Remove Substring

To remove all occurrences of a substring from a string, you can provide the replacement string as an empty string in the Regex.Replace() method as follows.

Download  Run Code

 
Sometimes you need to remove consecutive duplicate occurrences of a delimiter from a string. It can be easily done using the + quantifier, which matches one or more occurrences of the pattern.

Download  Run Code

That’s all about replacing all occurrences of a substring with another string in C#.