【问题标题】:Escape Special Character in Regex在正则表达式中转义特殊字符
【发布时间】:2013-12-28 15:29:29
【问题描述】:

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

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

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

正则表达式有内置函数吗?如果我必须从头开始编写一个函数,有没有一种方法可以轻松地计算所有字符,而不是一个一个地编写替换语句?

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

【问题讨论】:

  • Google 搜索 C# 转义特殊字符正则表达式会返回答案。
  • 可以说用户必须首先输入正确的 RE。如果您不知道它是否是特殊字符,则不能只转义随机字符。 (除非您当然不希望用户输入 RE,但问题是您为什么要使用 RE 进行查询)。

标签: c# regex escaping


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      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);
      

      【讨论】:

      • 这是很多不必要的工作来创建不正确的结果。
      猜你喜欢
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-25
      相关资源
      最近更新 更多