C#中正则表达式的简单使用

C#中有关正则表达式的类包含在System.Text.RegularExpressions命名空间中,可通过一下代码添加该命名空间:

1 using System.Text.RegularExpressions;
View Code

字符串匹配中,主角是"被匹配串"和"匹配模式"。

 1 // 定义 "被匹配串"
 2 string message = " mother father sister brother ";
 3 // 定义 "匹配模式"
 4 string pattern = @"\b(\w+)ther\b";
 5 // 用静态方法进行匹配,也可以通过创建正则对象进行匹配
 6 MatchCollection matches = Regex.Matches(message, pattern);
 7 // 遍历得到的结果
 8 foreach (Match match in matches) {
 9     Console.WriteLine("Groups[0].Value = {0} --- Groups[1].Value = {1}", match.Groups[0].Value, matchGroups[1].Value); 
10 } 
11 
12 // 输出
13 // Groups[0].Value = mother --- Groups[1].Value = mo
14 // Groups[0].Value = father --- Groups[1].Value = fa
15 // Groups[0].Value = brother --- Groups[1].Value = bro
16 // 结束输出

这是其中一个示例,匹配方法有三种: IsMatch(), Match(), Matches().

如果只是想知道"被匹配串"中是否包含某种"匹配模式", 可以使用IsMatch();

如果想得到一个匹配到的结果,可以使用Match();

如果想得到多个匹配到的结果,可以使用Matches();

单个匹配到的结果可以使用Groups[]获取利用"匹配模式"匹配的分组,以便对匹配得到的信息的利用。

 

 

具体使用规则:http://www.dotnetperls.com/regex-match

 

posted @ 2015-02-26 19:33  MchCyLh  阅读(103)  评论(0编辑  收藏  举报