Regex.Escape(String) Metoda

Definicja

Usuwa minimalny zestaw znaków (\, *, +, ?, |, {, [, (,), ^, $, ., #i biały znak), zastępując je kodami ucieczki. Spowoduje to, że aparat wyrażeń regularnych zinterpretuje te znaki dosłownie, a nie jako metacharactery.

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

Parametry

str
String

Ciąg wejściowy zawierający tekst do przekonwertowania.

Zwraca

Ciąg znaków z metacharacterami przekonwertowanymi na ich postać unikniętą.

Wyjątki

str to null.

Przykłady

Poniższy przykład wyodrębnia komentarze z tekstu. Przyjęto założenie, że komentarze są rozdzielane symbolem komentarza początku i symbolem komentarza końcowego wybranego przez użytkownika. Ponieważ symbole komentarza mają być interpretowane dosłownie, są przekazywane do Escape metody w celu zapewnienia, że nie mogą być błędnie interpretowane jako metacharacters. Ponadto przykład jawnie sprawdza, czy symbol komentarza końcowego wprowadzony przez użytkownika jest nawiasem zamykającym (]) lub nawiasem klamrowym (}). Jeśli tak jest, znak ukośnika odwrotnego (\) jest poprzedzany nawiasem klamrowym lub nawiasem klamrowym, aby był interpretowany dosłownie. Zwróć uwagę, że w przykładzie Match.Groups użyto również kolekcji do wyświetlania tylko komentarza, a nie komentarza razem z symbolami otwierania i zamykania komentarza.

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

Uwagi

Escape Konwertuje ciąg tak, aby aparat wyrażeń regularnych interpretował wszelkie metacharactery, które mogą zawierać jako literały znaków. Rozważmy na przykład wyrażenie regularne, które zostało zaprojektowane w celu wyodrębnienia komentarzy rozdzielonych prostymi nawiasami otwierającymi i zamykającymi ([ i ]) z tekstu. W poniższym przykładzie wyrażenie regularne "[(.*?)]" jest interpretowane jako klasa znaków. Zamiast dopasowywać komentarze osadzone w tekście wejściowym, wyrażenie regularne pasuje do każdego nawiasu otwierającego lub zamykającego, kropki, gwiazdki lub znaku zapytania.

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: .

Jeśli jednak nawias otwierający zostanie uniknięci przez przekazanie go do Escape metody, wyrażenie regularne powiedzie się w pasujących komentarzach osadzonych w ciągu wejściowym. Ilustruje to poniższy przykład.

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

W wyrażeniu regularnym, które jest definiowane przy użyciu tekstu statycznego, znaki, które mają być interpretowane dosłownie, a nie jako metacharactery, mogą być poprzedzone symbolem ukośnika odwrotnego (\), a także przez wywołanie Escape metody . W wyrażeniu regularnym, które jest definiowane dynamicznie przy użyciu znaków, które nie są znane w czasie projektowania, wywoływanie Escape metody jest szczególnie ważne, aby zapewnić, że aparat wyrażeń regularnych interpretuje poszczególne znaki jako literały, a nie jako metacharactery.

Uwaga

Jeśli wzorzec wyrażenia regularnego zawiera znak cyfry (#) lub znaki literału odstępu, należy je usunąć, jeśli tekst wejściowy jest analizowany z włączoną opcją RegexOptions.IgnorePatternWhitespace .

Escape Podczas gdy metoda ucieka przed prostym nawiasem otwierającym ([) i otwiera znaki nawiasu klamrowego ({), nie powoduje to ucieczki przed odpowiadającymi im znakami zamykającymi (] i }). W większości przypadków nie jest to konieczne. Jeśli nawias zamykający lub nawias klamrowy nie jest poprzedzony odpowiednim znakiem otwierającym, aparat wyrażeń regularnych interpretuje go dosłownie. Jeśli nawias otwierający lub nawias klamrowy jest interpretowany jako metatyp, aparat wyrażeń regularnych interpretuje pierwszy odpowiadający mu znak zamykający jako metatyp. Jeśli nie jest to pożądane zachowanie, nawias zamykający lub nawias klamrowy powinien być poprzedzony jawnie znakiem ukośnika odwrotnego (\). Aby zapoznać się z ilustracją, zobacz sekcję Przykład.

Dotyczy

Zobacz też