逃避正则表达式中的特殊角色

时间:2013-12-10 21:44:29

标签: c# regex escaping

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

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

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

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

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

3 个答案:

答案 0 :(得分:28)

您可以使用.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?]

答案 1 :(得分:9)

您可以将Regex.Escape用于用户的输入

答案 2 :(得分:0)

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