在正则表达式中转义特殊字符

26

有没有一种方法可以从字符串中转义正则表达式中的特殊字符,例如[]()*等?

基本上,我要求用户输入一个字符串,并且我想能够使用正则表达式在数据库中进行搜索。 我遇到的一些问题是too many)'s[x-y] range in reverse order等。

因此,我想编写一个函数来替换用户输入。例如,用\(替换(,用\[替换[

是否有内置的正则表达式函数可以这样做?如果我必须从头开始编写一个函数,是否有一种方法可以轻松地考虑所有字符,而不是一次编写一个替换声明?

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


在谷歌上搜索 C# 转义特殊字符 Regex 即可得到答案。 - Jim Mischel
可以说用户必须首先输入正确的正则表达式。如果您不知道它是特殊字符还是普通字符,就不能随意转义任意字符。(除非您不希望用户输入正则表达式,但这时问题是为什么要使用正则表达式进行查询)。 - eckes
3个回答

43

你可以使用.NET内置的Regex.Escape来完成这个任务。以下是从Microsoft的例子中复制出来的:

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

9

-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);

4
这需要做很多不必要的工作,却得到了错误的结果。 - Alan Moore

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接