一、正则表达式
正则表达式提供了功能强大、灵活而又高效的方法来处理文本。
正则表达式丰富的泛模式匹配表示法使你可以快速分析大量文本,以便:
- 查找特定字符模式
- 验证文本以确保它匹配预定义模式(如电子邮件地址)
- 提取、编辑、替换或删除文本子字符串
- 将提取的字符串添加到集合中,以便生成报告
对于处理字符串或分析大文本块的许多应用程序而言,正则表达式是不可缺少的工具。
二、正则表达式的工作方式
使用正则表达式进行文本处理的核心是正则表达式引擎,(由 .NET 中的 System.Text.RegularExpressions.Regex 对象表示)。 使用正则表达式处理文本至少要求向该正则表达式引擎提供以下两方面的信息:
- 要在文本中标识的正则表达式模式。
- 要为正则表达式模式分析的文本。
Regex 类的方法使你可以执行以下操作:
- 通过调用 Regex.IsMatch 方法确定输入文本中是否具有正则表达式模式。
- 通过调用 Regex.Match 或 Regex.Matches 方法检索匹配正则表达式模式的一个或所有文本匹配项。 第一个方法返回提供有关匹配文本的信息的 System.Text.RegularExpressions.Match 对象。 第二个方法返回 MatchCollection 对象,该对象对于在分析的文本中找到的每个匹配项包含一个 System.Text.RegularExpressions.Match 对象。
- 通过调用 Regex.Replace 方法替换匹配正则表达式模式的文本。
三、Regex类
看一下类的大概用法,后续用到在官方文档查具体的。
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
// RegxOptions.Compiled: 指定正则表达式编译为 MSIL 代码,而不是解释。
// 已编译的正则表达式最大限度地提高运行时性能,代价是会影响初始化时间。
RegexOptions.Compiled | RegexOptions.IgnoreCase);
string text = "The the quick brown fox fox jumps over the lazy dog dog.";
MatchCollection matches = rx.Matches(text);
Console.WriteLine("{0} matches found in:\n {1}",
matches.Count,
text);
foreach (Match match in matches)
{
GroupCollection groups = match.Groups;
Console.WriteLine("'{0}' repeated at positions {1} and {2}",
groups["word"].Value,
groups[0].Index,
groups[1].Index);
}
}
}
四、Match 类
表示单个正则表达式匹配的结果。
继承 Object Capture Group Match
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "int[] values = { 1, 2, 3 };\n" +
"for (int ctr = values.GetLowerBound(1); ctr <= values.GetUpperBound(1); ctr++)\n" +
"{\n" +
" Console.Write(values[ctr]);\n" +
" if (ctr < values.GetUpperBound(1))\n" +
" Console.Write(\", \");\n" +
"}\n" +
"Console.WriteLine();\n";
string pattern = @"Console\.Write(Line)?";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
Console.WriteLine("'{0}' found in the source code at position {1}.",
match.Value, match.Index);
}
}