Regex.Escape(String) 方法

定义

将一组最小字符 (\、*、+、?、|、{、[、 (、) 、^、$、.、#和空格) 转义。 这将指示正则表达式引擎按原义解释这些字符而不是解释为元字符。

C#
public static string Escape(string str);

参数

str
String

包含要转换的文本的输入字符串。

返回

由转换为转义形式的元字符组成的字符串。

例外

strnull

示例

以下示例从文本中提取注释。 它假定注释由用户选择的开始注释符号和结束注释符号分隔。 由于注释符号要按字面解释,因此会将其传递给 Escape 方法,以确保它们不会被错误解释为元字符。 此外,该示例还显式检查用户输入的结束注释符号是右括号 (]) 还是大括号 (}) 。 如果是,则反斜杠字符 (\) 在括号或大括号前附加,以便按字面解释它。 请注意,该示例还使用 Match.Groups 集合来仅显示注释,而不是注释及其开始和结束注释符号。

C#
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      ConsoleKeyInfo keyEntered;
      char beginComment, endComment;
      Console.Write("Enter begin comment symbol: ");
      keyEntered = Console.ReadKey();
      beginComment = keyEntered.KeyChar;
      Console.WriteLine();
      
      Console.Write("Enter end comment symbol: ");
      keyEntered = Console.ReadKey();
      endComment = keyEntered.KeyChar;
      Console.WriteLine();
      
      string input = "Text [comment comment comment] more text [comment]";
      string pattern;
      pattern = Regex.Escape(beginComment.ToString()) + @"(.*?)";
      string endPattern = Regex.Escape(endComment.ToString());
      if (endComment == ']' || endComment == '}') endPattern = @"\" + endPattern;
      pattern += endPattern;
      MatchCollection matches = Regex.Matches(input, pattern);
      Console.WriteLine(pattern);
      int commentNumber = 0;
      foreach (Match match in matches)
         Console.WriteLine("{0}: {1}", ++commentNumber, match.Groups[1].Value);
   }
}
// The example shows possible output from the example:
//       Enter begin comment symbol: [
//       Enter end comment symbol: ]
//       \[(.*?)\]
//       1: comment comment comment
//       2: comment

注解

Escape 转换字符串,以便正则表达式引擎将它可能包含的任何元字符解释为字符文本。 例如,假设有一个正则表达式,该正则表达式旨在从文本中提取由直括号和右括号 ([ 和 ]) 分隔的注释。 在以下示例中,正则表达式“[ (.*?) ]”被解释为字符类。 正则表达式匹配每个左括号或右括号、句点、星号或问号,而不是输入文本中嵌入的匹配注释。

C#
string pattern = "[(.*?)]"; 
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: ?
//          2: ?
//          3: .

但是,如果通过将左方括号传递给 方法对它 Escape 进行转义,则正则表达式将成功匹配嵌入在输入字符串中的注释。 下面的示例对此进行了演示。

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

在使用静态文本定义的正则表达式中,可以通过在字符前面使用反斜杠符号 (\) 以及调用 Escape 方法对字符进行字面解释而不是元字符的字符进行转义。 在使用设计时未知的字符动态定义的正则表达式中,调用 Escape 方法对于确保正则表达式引擎将单个字符解释为文本而不是元字符尤为重要。

备注

如果正则表达式模式包含数字符号 (#) 或文本空格字符,则必须在分析输入文本并 RegexOptions.IgnorePatternWhitespace 启用 选项时转义它们。

虽然Escape方法可转义直接打开方括号 ([),并打开大括号 ({) 字符,它未转义其对应的结束字符 (] 和})。 在大多数情况下,不需要转义这些内容。 如果右括号或大括号的前面没有相应的开始字符,则正则表达式引擎会按字面解释它。 如果将左括号或大括号解释为元字符,则正则表达式引擎会将第一个对应的结束字符解释为元字符。 如果这不是所需行为,则应通过在反斜杠 (\) 字符前面显式附加反斜杠来转义右括号或大括号。 有关插图,请参阅示例部分。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另请参阅