当正则表达式匹配子表达式的时候,产生了一个被称为是Capture的对象,而且会把此对象添加到名为CapturesCollection的集合里面。当在正则表达中使用命名组的时候,这个组就有自己的捕获集合。
为了检索用了命名组的正则表达式所收集的捕获,就要调用来自match对象group属性的Captures属性。在这个实例中是很容易理解的。利用前面的例子,下面代码返回了在字符串中找到的所有日期和年龄,而且日期和年龄是完全分组的:
string dates = "08/14/57 46 02/25/59 45 06/05/85 18 03/12/88 16 09/09/90 13";
string regExp = "(?<dates>(\\d{2}/\\d{2}/\\d{2}))\\s(?<ages>(\\d{2}))\\s";
MatchCollection matchSet = Regex.Matches(dates,regExp);
Console.WriteLine();
foreach (Match aMatch in matchSet)
{
foreach (Capture aCapture in aMatch.Groups["dates"].Captures)
Console.WriteLine("date capture:{0}",aCapture.ToString());
foreach (Capture aCapture in aMatch.Groups["ages"].Captures)
Console.WriteLine("age capture:{0}",aCapture.ToString());
}