sor*_*419 18 c# regex escaping
有没有办法[]()*从字符串中转义正则表达式中的特殊字符,例如和其他字符?
基本上,我要求用户输入一个字符串,我希望能够使用正则表达式在数据库中搜索.我遇到的一些问题是too many)'s或[x-y] range in reverse order等等.
所以我想要做的是编写一个函数来替换用户输入.例如,替换(为\(,替换[为\[
是否有正则表达式的内置函数?如果我必须从头开始编写函数,是否有办法轻松地对所有字符进行编码而不是逐个编写替换语句?
我正在使用Visual Studio 2010在C#中编写程序
bra*_*ipt 29
您可以使用.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?]
Run Code Online (Sandbox Code Playgroud)