Regex.Escape(String) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将一组最小字符 (\、*、+、?、|、{、[、 (、) 、^、$、.、#和空格) 转义。 这将指示正则表达式引擎按原义解释这些字符而不是解释为元字符。
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
包含要转换的文本的输入字符串。
返回
由转换为转义形式的元字符组成的字符串。
例外
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方法可转义直接打开方括号 ([),并打开大括号 ({) 字符,它未转义其对应的结束字符 (] 和})。 在大多数情况下,不需要转义这些内容。 如果右括号或大括号的前面没有相应的开始字符,则正则表达式引擎会按字面解释它。 如果将左括号或大括号解释为元字符,则正则表达式引擎会将第一个对应的结束字符解释为元字符。 如果这不是所需行为,则应通过在反斜杠 (\) 字符前面显式附加反斜杠来转义右括号或大括号。 有关插图,请参阅示例部分。