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

변환할 텍스트가 포함된 입력 문자열입니다.

반환

String

메타문자가 이스케이프 서식으로 변환된 문자열입니다.

예외

str이(가) null인 경우

예제

다음 예제에서는 텍스트에서 주석을 추출합니다. 주석은 사용자가 선택한 시작 주석 기호 및 끝 주석 기호로 구분된다고 가정합니다. 주석 기호는 문자 그대로 해석되므로 메타 문자로 잘못 해석될 수 없도록 메서드에 전달 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 직선 여는 대괄호([) 및 여는 중괄호({) 문자를 이스케이프하지만 해당 닫는 문자(] 및 })를 이스케이프하지 않습니다. 대부분의 경우 이스케이프가 필요하지 않습니다. 닫는 대괄호 또는 중괄호 앞에 해당 여는 문자가 없는 경우 정규식 엔진은 문자 그대로 해석합니다. 여는 대괄호 또는 중괄호가 메타 문자로 해석되는 경우 정규식 엔진은 첫 번째 해당 닫는 문자를 메타 문자로 해석합니다. 원하는 동작이 아닌 경우 백슬래시(\) 문자를 명시적으로 앞에 추가하여 닫는 대괄호 또는 중괄호를 이스케이프해야 합니다. 일러스트레이션은 예제 섹션을 참조하세요.

적용 대상

추가 정보