本文整理匯總了C#中System.Text.RegularExpressions.Regex.Escape方法的典型用法代碼示例。如果您正苦於以下問題:C# Regex.Escape方法的具體用法?C# Regex.Escape怎麽用?C# Regex.Escape使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Text.RegularExpressions.Regex
的用法示例。
在下文中一共展示了Regex.Escape方法的3個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Main
//引入命名空間
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
示例2:
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);
輸出:
[(.*?)] produces the following matches: 1: ? 2: ? 3: .
示例3:
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);
輸出:
\[(.*?)] produces the following matches: 1: [what kind?] 2: [by whom?]