25

Is there a way to escape the special characters in regex, such as []()* and others, from a string?

Basically, I'm asking the user to input a string, and I want to be able to search in the database using regex. Some of the issues I ran into are too many)'s or [x-y] range in reverse order, etc.

So what I want to do is write a function to do replace on the user input. For example, replacing ( with \(, replacing [ with \[

Is there a built-in function for regex to do so? And if I have to write a function from scratch, is there a way to account all characters easily instead of writing the replace statement one by one?

I'm writing my program in C# using Visual Studio 2010

sora0419
  • 2,308
  • 9
  • 39
  • 58
  • A Google search on *C# escape special character regex* returns the answer. – Jim Mischel Dec 10 '13 at 22:30
  • It can be argued the user has to enter correct RE in the first place. You cant just escape random character if you dont know if it is a special character or not. (Unless you don't want the user to enter RE of course, but then the questin is why would you use RE for the query). – eckes Mar 23 '15 at 03:23

3 Answers3

42

You can use .NET's built in Regex.Escape for this. Copied from Microsoft's example:

string pattern = Regex.Escape("[") + "(.*?)]"; 
string input = "The animal [what kind?] was visible [by whom?] from the window.";

MatchCollection matches = Regex.Matches(input, pattern);
int commentNumber = 0;
Console.WriteLine("{0} produces the following matches:", pattern);
foreach (Match match in matches)
   Console.WriteLine("   {0}: {1}", ++commentNumber, match.Value);  

// This example displays the following output: 
//       \[(.*?)] produces the following matches: 
//          1: [what kind?] 
//          2: [by whom?]
brandonscript
  • 68,675
  • 32
  • 163
  • 220
9

you can use Regex.Escape for the user's input

L.B
  • 114,136
  • 19
  • 178
  • 224
-1
string matches = "[]()*";
StringBuilder sMatches = new StringBuilder();
StringBuilder regexPattern = new StringBuilder();
for(int i=0; i<matches.Length; i++)
    sMatches.Append(Regex.Escape(matches[i].ToString()));
regexPattern.AppendFormat("[{0}]+", sMatches.ToString());

Regex regex = new Regex(regexPattern.ToString());
foreach(var m in regex.Matches("ADBSDFS[]()*asdfad"))
    Console.WriteLine("Found: " + m.Value);