20.5.3 开始使用正则表达式
我们从一个简单的匹配开始,先看代码,如代码清单20-11所示。代码虽然很简单,但已经是“麻雀虽小,五脏俱全”。在代码中,我们使用了一个简单的正则表达式"csharp4.0",这里采用的是实例化Regex对象再执行搜索的方式,调用的是实例方法Matches,然后迭代搜索的结果MatchCollection集合,最后打印找到的每一个匹配项(Match对象)所包含的信息,这包括匹配项的索引和匹配项的值。
代码清单20-11 一个简单的匹配示例
using System;
using System.Text.RegularExpressions;
namespace ProgrammingCSharp4
{
class RegexSample
{
public static void Main()
{
string pattern="csharp4.0";
string text="This is a book about csharp4.0!Wish you like it!";
Regex regex=new Regex(pattern);
MatchCollection results=regex.Matches(text);
foreach(Match match in results)
{
Console.WriteLine(“在索引{0}处发现目标({1})!”,match.Index,match.Value);
}
}
}
}
上述代码的运行结果为:
在索引21处发现目标(csharp4.0)!
请按任意键继续……
再使用第二种方式,即使用静态方法的方式来执行搜索。只需要将代码清单20-11中的如下代码。
Regex regex=new Regex(pattern);
MatchCollection results=regex.Matches(text);
替换为:
MatchCollection results=Regex.Matches(text,pattern);
接下来,我们看一个使用了“组”概念的表达式的例子。在代码清单20-12中,我们定义了一个正则表达式字符串如下:
"The([a-z]{3})that made no([a-z]{5})some\2 again"
正则表达式引擎会记忆"()"中匹配到的内容,作为一个“组”。在该表达式中有两个分组,第一个是包含3个英文字符的字符串,第二个是包含5个英文字符的字符串,表达式中的"\2"表示引用表达式中的第二个组。当然,"\1"表示第一个组。
代码清单20-12 分组和后向引用的示例
using System;
using System.Text.RegularExpressions;
namespace ProgrammingCSharp4
{
class RegexSample
{
public static void Main()
{
string x="The cat that made nothing something again";
string y="The cat that made nothing again";
string pattern=@"The([a-z]{3})that made no([a-z]{5})some\2 again";
Regex r=new Regex(pattern);
Console.WriteLine("x match count:"+r.Matches(x).Count);
Console.WriteLine("y match count:"+r.Matches(y).Count);
r=new Regex(pattern);
if(r.IsMatch(x))
{
for(int i=0;i<r.Match(x).Groups.Count;i++)
{
Console.WriteLine("group{0}value:{1}",i,
r.Match(x).Groups[i].Value);//输出:thing
}
}
}
}
}
上述代码的运行结果如下:
x match count:1
y match count:0
group0 value:The cat that made nothing something again
group1 value:cat
group2 value:thing
请按任意键继续……
索引为0的分组是默认分组,值为整个匹配的字符串。