Regex.Escape(String) Regex.Escape(String) Regex.Escape(String) Regex.Escape(String) Method

定義

文字 (\、*、+、?、|、{、[、(、)、^、$、.、#、および空白) をエスケープ コードに置き換えることにより、このような文字をエスケープします。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 String String String

変換対象のテキストを含んでいる入力文字列。The input string that contains the text to convert.

戻り値

メタ文字がエスケープされた形式に変換された文字列。A string of characters with metacharacters converted to their escaped form.

例外

次の例では、テキストからコメントを抽出します。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.

適用対象

こちらもご覧ください