Regex.Escape(String) 方法

定義

以逸出程式碼取代字元 (\、*、+、?、|、{、[、(、)、^、$、.、# 和空白字元) 的最小集合,以便逸出這些字元。Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $, ., #, and white space) by replacing them with their escape codes. 這樣會指示規則運算式引擎將這些字元解譯為常值,而非解譯為中繼字元。This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.

public:
 static System::String ^ Escape(System::String ^ str);
public static string Escape (string str);
static member Escape : string -> string
Public Shared Function Escape (str As String) As String

參數

str
String

輸入字串,包含要轉換的文字。The input string that contains the text to convert.

傳回

字元字串,其中中繼字元已轉換為逸出格式。A string of characters with metacharacters converted to their escaped form.

例外狀況

strnullstr is null.

範例

下列範例會從文字中解壓縮批註。The following example extracts comments from text. 它假設批註是以開始批註符號和使用者選取的結束批註符號來分隔。It assumes that the comments are delimited by a begin comment symbol and an end comment symbol that is selected by the user. 因為批註符號是以字面Escape方式轉譯, 所以會傳遞至方法, 以確保它們無法被誤解為「元字元」。Because the comment symbols are to be interpreted literally, they are passed to the Escape method to ensure that they cannot be misinterpreted as metacharacters. 此外, 此範例會明確地檢查使用者所輸入的結束批註符號是否為右括弧 (]) 或大括弧 (})。In addition, the example explicitly checks whether the end comment symbol entered by the user is a closing bracket (]) or brace (}). 如果是, 則會在括弧或\大括弧前面加上反斜線字元 (), 讓它以字面方式解讀。If it is, a backslash character (\) is prepended to the bracket or brace so that it is interpreted literally. 請注意, 此範例也會Match.Groups使用集合來顯示批註, 而不是批註連同其開頭和結尾批註符號。Note that the example also uses the Match.Groups collection to display the comment only, rather than the comment together with its opening and closing comment symbols.

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
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim keyEntered As ConsoleKeyInfo
      Dim beginComment, endComment As Char
      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()
      
      Dim input As String = "Text [comment comment comment] more text [comment]"
      Dim pattern As String = Regex.Escape(beginComment.ToString()) + "(.*?)"
      Dim endPattern As String = Regex.Escape(endComment.ToString())
      If endComment = "]"c OrElse endComment = "}"c Then endPattern = "\" + endPattern
      pattern += endPattern
      
      Dim matches As MatchCollection = Regex.Matches(input, pattern)
      Console.WriteLine(pattern)
      Dim commentNumber As Integer = 0
      For Each match As Match In matches
         commentNumber += 1
         Console.WriteLine("{0}: {1}", commentNumber, match.Groups(1).Value)
      Next         
   End Sub
End Module
' The example shows possible output from the example:
'       Enter begin comment symbol: [
'       Enter end comment symbol: ]
'       \[(.*?)\]
'       1: comment comment comment
'       2: comment

備註

Escape轉換字串, 讓正則運算式引擎會解讀其可包含為字元常值的任何元字元。Escape converts a string so that the regular expression engine will interpret any metacharacters that it may contain as character literals. 例如, 假設有一個正則運算式, 其設計目的是要從文字中解壓縮以直接左和右方括弧 ([和]) 分隔的批註。For example, consider a regular expression that is designed to extract comments that are delimited by straight opening and closing brackets ([ and ]) from text. 在下列範例中, 正則運算式 "[(. *?)]" 會解讀為字元類別。In the following example, the regular expression "[(.*?)]" is interpreted as a character class. 正則運算式不會比對內嵌在輸入文字中的批註, 而是會符合每個左右括弧、句號、星號或問號。Rather than matching comments embedded in the input text, the regular expression matches each opening or closing parenthesis, period, asterisk, or question mark.

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: .
Dim pattern As String = "[(.*?)]" 
Dim input As String = "The animal [what kind?] was visible [by whom?] from the window."

Dim matches As MatchCollection = Regex.Matches(input, pattern)
Dim commentNumber As Integer = 0
Console.WriteLine("{0} produces the following matches:", pattern)
For Each match As Match In matches
   commentNumber += 1
   Console.WriteLine("{0}: {1}", commentNumber, match.Value)       
Next      
' This example displays the following output:
'       1: ?
'       2: ?
'       3: .

不過, 如果左括弧是藉由將它傳遞至Escape方法來進行轉義, 則正則運算式會成功地比對輸入字串中內嵌的批註。However, if the opening bracket is escaped by passing it to the Escape method, the regular expression succeeds in matching comments that are embedded in the input string. 下列範例將說明這點。The following example illustrates this.

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?]
Dim pattern As String = Regex.Escape("[") + "(.*?)]" 
Dim input As String = "The animal [what kind?] was visible [by whom?] from the window."

Dim matches As MatchCollection = Regex.Matches(input, pattern)
Dim commentNumber As Integer = 0
Console.WriteLine("{0} produces the following matches:", pattern)
For Each match As Match In matches
   commentNumber += 1
   Console.WriteLine("   {0}: {1}", commentNumber, match.Value)  
Next
' This example displays the following output:
'       \[(.*?)] produces the following matches:
'          1: [what kind?]
'          2: [by whom?]

在使用靜態文字所定義的正則運算式中, 可以使用反斜線符號 (\) 以及Escape呼叫方法, 來將要以字面方式解讀而非元字元的字元加以轉義。In a regular expression that is defined by using static text, characters that are to be interpreted literally rather than as metacharacters can be escaped by preceding them with a backslash symbol (\) as well as by calling the Escape method. 在使用設計階段不知道的字元動態定義的正則運算式中, 呼叫Escape方法特別重要, 以確保正則運算式引擎會將個別字元解讀為常值, 而不是作為「元字元」。In a regular expression that is defined dynamically using characters that are not known at design time, calling the Escape method is particularly important to ensure that the regular expression engine interprets individual characters as literals rather than as metacharacters.

注意

如果正則運算式模式包含數位記號 (#) 或常值空白字元, 則必須在已啟用選項的RegexOptions.IgnorePatternWhitespace情況下剖析輸入文字時, 才會將其轉義。If a regular expression pattern includes either the number sign (#) or literal white-space characters, they must be escaped if input text is parsed with the RegexOptions.IgnorePatternWhitespace option enabled.

雖然Escape方法會逸出直接開啟括號 ([),並開啟括號 ({}) 字元,它不會逸出其對應的結尾字元 (] 和})。While the Escape method escapes the straight opening bracket ([) and opening brace ({) characters, it does not escape their corresponding closing characters (] and }). 在大部分的情況下, 不需要進行轉義。In most cases, escaping these is not necessary. 如果右括弧或大括弧前面沒有對應的開頭字元, 正則運算式引擎會將它逐字解讀。If a closing bracket or brace is not preceded by its corresponding opening character, the regular expression engine interprets it literally. 如果將左括弧或大括弧視為元字元, 正則運算式引擎會將第一個對應的結尾字元解讀為「元字元」。If an opening bracket or brace is interpreted as a metacharacter, the regular expression engine interprets the first corresponding closing character as a metacharacter. 如果這不是所需的行為, 則必須明確預先加上反斜線 (\) 字元, 以將右括弧或大括弧進行轉義。If this is not the desired behavior, the closing bracket or brace should be escaped by explicitly prepending the backslash (\) character. 如需圖例, 請參閱範例一節。For an illustration, see the Example section.

適用於

另請參閱