共用方式為


Regex.Escape(String) 方法

定義

藉由以逸出碼取代字元,以逸出字元集 (\、*、+、?、|、{、[、 (、) 、^、$、.、#和空白字元) 。 這樣會指示規則運算式引擎將這些字元解譯為常值,而非解譯為中繼字元。

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

輸入字串,包含要轉換的文字。

傳回

字元字串,其中中繼字元已轉換為逸出格式。

例外狀況

strnull

範例

下列範例會從文字擷取批註。 它會假設批註是以開始批註符號和使用者選取的結束批註符號分隔。 由於批註符號會以常值方式解譯,因此會傳遞至 Escape 方法,以確保它們無法誤譯為中繼字元。 此外,此範例會明確檢查使用者輸入的結尾批註符號是否為右括弧 (]) 或大括弧 (}) 。 如果是,反斜線字元 (\) 前面會加上括弧或大括弧,以便以常值方式解譯。 請注意,此範例也會使用 Match.Groups 集合只顯示批註,而不是批註及其開頭和結尾批註符號。

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 會轉換字串,讓正則運算式引擎將它可能包含的任何中繼字元解譯為字元常值。 例如,請考慮正則運算式,其設計目的是從文字中擷取以直接開頭和右括弧分隔的批註, ([ 和 ]) 。 在下列範例中,正則運算式 「[ (.*?) ]」 會解譯為字元類別。 正則運算式會比對內嵌在輸入文字中的批註,而是會比對每個左右括弧、句號、星號或問號。

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 方法以逸出,則正則運算式會成功比對內嵌在輸入字串中的批註。 下列範例將說明這點。

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 方法來逸出。 在動態定義的正則運算式中,使用設計階段不知道的字元,呼叫 Escape 方法特別重要,以確保正則運算式引擎會將個別字元解譯為常值,而不是中繼字元。

注意

如果正則運算式模式包含數位記號 (#) 或常值空白字元,則必須在輸入文字剖析並 RegexOptions.IgnorePatternWhitespace 啟用選項時逸出。

雖然Escape方法會逸出直接開啟括號 ([),並開啟括號 ({}) 字元,它不會逸出其對應的結尾字元 (] 和})。 在大部分情況下,不需要逸出這些專案。 如果右括弧或大括弧前面沒有對應的開頭字元,則正則運算式引擎會以常值方式解譯它。 如果左括弧或大括弧解譯為中繼字元,正則運算式引擎會將第一個對應的結尾字元解譯為中繼字元。 如果這不是所需的行為,應該藉由明確地在反斜線 (\) 字元前面加上括弧或大括弧來逸出。 如需圖例,請參閱一節。

適用於

另請參閱