GroupCollection Class、Regex.GetGroupNumbers()、Regex.GetGroupNames()
GroupCollection Class 有三個值得注意的屬性
一、Count
在一輪的比對中,用來取得分群的數量
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string input = "abc-bob add-but ";
string pattern = @"(a\w+)-(b\w+)\s";
Match match = Regex.Match(input, pattern);
while (match.Success)
{
for (int groupsCount = 0; groupsCount < match.Groups.Count; groupsCount++)
{
Console.WriteLine(match.Groups[groupsCount].Value);
}
match = match.NextMatch();
}
}
}
其結果為
說明:
上例中 GroupCollection.Count 為 3,表示第一輪的比對,
其分群有兩個(第一個為整個群組的值,不把他算在內),
分別為 abc 與 bob。
二、GroupCollection[Int32]
用來取得第 n 個分群的 Group 物件
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string input = "abc-bob add-but ";
string pattern = @"(a\w+)-(b\w+)\s";
Match match = Regex.Match(input, pattern);
while (match.Success)
{
for (int groupsCount = 0; groupsCount < match.Groups.Count; groupsCount++)
{
Group g = match.Groups[groupsCount];
Console.WriteLine(g.Value);
}
match = match.NextMatch();
}
}
}
其結果為
三、GroupCollection[String]
用來取得某命名分群的 Group 物件
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string input = "abc-bob add-but ";
string pattern = @"(?<myA>a\w+)-(?<myB>b\w+)\s";
Match match = Regex.Match(input, pattern);
while (match.Success)
{
Group ga = match.Groups["myA"];
Console.WriteLine("myA = " + ga.Value);
Group gb = match.Groups["myB"];
Console.WriteLine("myB = " + gb.Value);
match = match.NextMatch();
}
}
}
其結果為
四、Regex.GetGroupNumbers Method
用來取得分群的 index(第一個表示為一整個群組,不把他算在內)
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string input = "abc-bob add-but ";
string pattern = @"(a\w+)-(b\w+)\s";
Regex rgx = new Regex(pattern);
int[] groupNumbers = rgx.GetGroupNumbers();
for (int i = 0; i < groupNumbers.Length; i++)
{
Console.WriteLine(groupNumbers[i]);
}
}
}
其結果為
五、Regex.GetGroupNames Method
用來取得分群的名稱(第一個表示為一整個群組,不把他算在內)
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string input = "abc-bob add-but ";
string pattern = @"(?<myA>a\w+)-(?<myB>b\w+)\s";
Regex rgx = new Regex(pattern);
string[] groupNames = rgx.GetGroupNames();
for (int i = 0; i < groupNames.Length; i++)
{
Console.WriteLine(groupNames[i]);
}
}
}
其結果為