1

I have a string. I need to replace all instances of a given array of strings from this original string - how would I do that?

Currently I am using...

var inputString = "this is my original string.";
var replacement = "";
var pattern = string.Join("|", arrayOfStringsToRemove);

Regex.Replace(inputString, pattern, replacement);

This works fine, but unfortunately it breaks down when someone tries to remove a character that has a special meaning in the regex.

How should I do this? Is there a better way?

KevinT
  • 3,094
  • 4
  • 26
  • 29

4 Answers4

3

Build the pattern using Regex.Escape:

StringBuilder pattern = new StringBuilder();
foreach (string s in arrayOfStringsToRemove)
{
    pattern.Append("(");
    pattern.Append(Regex.Escape(s));
    pattern.Append(")|");
}
Regex.Replace(inputString, pattern.ToString(0, pattern.Length - 1), // remove trailing |
    replacement);
gimel
  • 83,368
  • 10
  • 76
  • 104
1

Look at Regex.Escape

leppie
  • 115,091
  • 17
  • 196
  • 297
0

You need to escape special characters with a backslash

\

Sometimes you may need to use two backslashes

\\
adam
  • 22,404
  • 20
  • 87
  • 119
0

You need to escape characters with spacial meaning of course.

var str_to_replace = "removing \[this\]\(link\)";
muhuk
  • 15,777
  • 9
  • 59
  • 98