C# 正则表达式

来源:互联网 发布:剑灵小秦夕颜捏脸数据 编辑:程序博客网 时间:2024/05/29 08:32

Match、MatchCollection、Group、GroupCollection   用法示例 与实践

 

一次Match获得一个MatchCollection

一个MatchCollection 可能包含多个Match

 

一个Match可以包含一个GroupCollection

一个GroupCollection中包含多个匹配的group

 

只要熟练的掌握它们应该就可以从字符串里面截取自己需要的东东了。

 

1. 头文件

using System.Text.RegularExpressions;

 

2. 用法示例

 

2.1  Match

string myString = "a sailor went to sea to see," + "to see what he could see, could see.";
Regex rxToMatch = new Regex(@"se.");
Match newMatchMade = rxToMatch.Match(myString);

while (newMatchMade.Success)
{
    Console.WriteLine(newMatchMade.Value.ToString());
    newMatchMade = newMatchMade.NextMatch();

}

2.2  GroupCollection & group

Regex matchRegex = new Regex(@"^<span style='color:(/#/w{6})'>(.*)</span>$");
Match matchMade = matchRegex.Match("<span style='color:#cc0033'>测试</span>");
GroupCollection matchGroups = matchMade.Groups;

foreach (Group group in matchGroups){ 
    Console.WriteLine(group.Value);
}

注意: 因为Group[0]返回的是你匹配的整个字符串 Group[1]Group[2]……才是你的正则中捕获的组的内容

 

 

2.3  MatchCollection And Groups

 

string rxLinePattern = @"/n(/s)*(.+)-(.+)-/s(?<lineName0>(.+))/s-(.+)/n(/s)*出发:(/s)+(?<startStation0>(.+))/n(/s)*到达:(/s)+(?<endStation0>(.+))/n";

string inputString =
@"公交 - 498路 - 498路(中央党校北门--新街口豁口) - 方向: 新街口豁口
出发: 中关园北站 
 10.1 公里
到达: 新街口豁口 
 
公交 - 498路 - 498路(中央党校北门--新街口豁口) - 方向: 新街口豁口
出发:  中关园北站
到达:  新街口豁口
 
« 上一步 放大
行程概述 下一步 »
 
 
地铁 - 地铁2号线 - 地铁2号线内环(西直门--西直门) - 方向: 西直门
出发: 积水潭 
到达: 北京站
";

 

MatchCollection matchesMade = Regex.Matches(inputString, rxLinePattern);

Console.WriteLine(matchesMade.Count);
for (int i = 0; i < matchesMade.Count; i++)
{
    Console.WriteLine(matchesMade[i].Groups["startStation0"].Value.ToString());
    Console.WriteLine(matchesMade[i].Groups["endStation0"].Value.ToString());
}

原创粉丝点击