標籤:
http://www.cnblogs.com/kiant71/archive/2010/08/14/1799799.html
在一個Regex中,如果要提取出多個不同的部分(子運算式項),需要用到分組功能。
在 C# Regex中,Regex 成員關係如下,其中 Group 是其分組處理類。
Regex –> MatcheCollection (匹配項集合)
–> Match (單匹配項 內容)
–> GroupCollection (單匹配項中包含的 "(分組/子運算式項)" 集合)
–> Group ( "(分組/子運算式項)" 內容)
–> CaputerCollection (分組項內容顯示基礎?)
–> Caputer
Group 對分組有兩種訪問方式:
1、數組下標訪問
在 ((\d+)([a-z]))\s+ 這個Regex裡總共包含了四個分組,按照預設的從左至右的匹配方式,
Groups[0] 代表了匹配項本身,也就是整個整個運算式 ((\d+)([a-z]))\s+
Groups[1] 代表了子運算式項 ((\d+)([a-z]))
Groups[2] 代表了子運算式項 (\d+)
Groups[3] 代表了子運算式項 ([a-z])
| 1234567891011121314151617181920212223242526272829303132333435363738 |
string text = "1A 2B 3C 4D 5E 6F 7G 8H 9I 10J 11Q 12J 13K 14L 15M 16N ffee80 #800080";Response.Write(text + "<br/>"); string strPatten = @"((\d+)([a-z]))\s+";Regex rex = new Regex(strPatten, RegexOptions.IgnoreCase);MatchCollection matches = rex.Matches(text); //提取匹配項foreach (Match match in matches){ GroupCollection groups = match.Groups; Response.Write(string.Format("<br/>{0} 共有 {1} 個分組:{2}<br/>" , match.Value, groups.Count, strPatten)); //提取匹配項內的分組資訊 for (int i = 0; i < groups.Count; i++) { Response.Write( string.Format("分組 {0} 為 {1},位置為 {2},長度為 {3}<br/>" , i , groups[i].Value , groups[i].Index , groups[i].Length)); }} /* * 輸出: 1A 2B 3C 4D 5E 6F 7G 8H 9I 10J 11Q 12J 13K 14L 15M 16N ffee80 #800080 1A 共有 4 個分組:((\d+)([a-z]))\s+分組 0 為 1A ,位置為 0,長度為 3分組 1 為 1A,位置為 0,長度為 2分組 2 為 1,位置為 0,長度為 1分組 3 為 A,位置為 1,長度為 1 .... */ |
2、命名訪問
利用 (?<xxx>子運算式) 定義分組別名,這樣就可以利用 Groups["xxx"] 進行訪問分組/子運算式內容。
| 12345678910111213141516171819202122232425 |
string text = "I‘ve found this amazing URL at http://www.sohu.com, and then find ftp://ftp.sohu.comisbetter.";Response.Write(text + "<br/>"); string pattern = @"\b(?<protocol>\S+)://(?<address>\S+)\b";Response.Write(pattern.Replace("<", "<").Replace(">",">") + "<br/><br/>"); MatchCollection matches = Regex.Matches(text, pattern);foreach (Match match in matches){ GroupCollection groups = match.Groups; Response.Write(string.Format( "URL: {0}; Protocol: {1}; Address: {2} <br/>" , match.Value , groups["protocol"].Value , groups["address"].Value));} /* * 輸出 I‘ve found this amazing URL at http://www.sohu.com, and then find ftp://ftp.sohu.comisbetter. \b(?<protocol>\S+)://(?<address>\S+)\b URL: http://www.sohu.com; Protocol: http; Address: www.sohu.com URL: ftp://ftp.sohu.comisbetter; Protocol: ftp; Address: ftp.sohu.comisbetter */ |
內容參考自:
C#Regex編程(三):Match類和Group類用法 http://blog.csdn.net/zhoufoxcn/archive/2010/03/09/5358644.aspx
C#Regex類Match和Group類的理解 http://tech.ddvip.com/2008-10/122483707982616.html
C# 中Regex Group 分組【轉】