简体   繁体   English

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

[英]Escape Special Character in Regex

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 [xy] range in reverse order , etc.我遇到的一些问题too many)'s[xy] range in reverse order ,等等。

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我正在使用 Visual Studio 2010 在 C# 中编写我的程序

You can use .NET's built in Regex.Escape for this. 为此,您可以使用 .NET 内置的Regex.Escape 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?]

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM