在正则表达式中逃避特殊性格

有没有办法从字符串中转义正则表达式中的特殊字符,例如[]()*和其他字符?

基本上,我要求用户输入一个字符串,我希望能够使用正则表达式在数据库中进行搜索。 我碰到的一些问题too many)'s或者[xy] range in reverse order等等。

所以我想要做的是编写一个函数来替换用户输入。 例如,替换(\( ,替换[ with \[

是否有正则表达式的内置函数? 如果我必须从头开始编写函数,是否有办法轻松地对所有字符进行编码,而不是逐个编写替换语句?

我正在使用Visual Studio 2010在C#中编写程序

您可以使用.NET内置的Regex.Escape 。 从微软的例子复制:

 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?] 

您可以使用Regex.Escape作为用户的输入

 string matches = "[]()*"; StringBuilder sMatches = new StringBuilder(); StringBuilder regexPattern = new StringBuilder(); for(int i=0; i