下面是使用CaptureCollections的另一个选项(在单个正则表达式中执行此操作的唯一方法)。菲尔罗斯的答案在一场比赛中完成了这一切,这场比赛有多场比赛。这样,所有的个人项目捕获都根据它们被发现的支架对进行适当分组。
string s = @"[1,2,3,4,5] [abc,ef,g] [0,2,4b,y7] ";
Regex r = new Regex(@"\[((?:([^,\[\]]+),?)*)\]");
int matchNum = 0;
foreach (Match m in r.Matches(s))
{
Console.WriteLine("Match {0}, Group 1: {1}", ++matchNum, m.Groups[1]);
int captureNum = 0;
foreach (Capture c in m.Groups[2].Captures)
{
Console.WriteLine(" Group 2, Capture {0}: {1}", ++captureNum, c);
}
}
输出:
Match 1, Group 1: 1,2,3,4,5
Group 2, Capture 1: 1
Group 2, Capture 2: 2
Group 2, Capture 3: 3
Group 2, Capture 4: 4
Group 2, Capture 5: 5
Match 2, Group 1: abc,ef,g
Group 2, Capture 1: abc
Group 2, Capture 2: ef
Group 2, Capture 3: g
Match 3, Group 1: 0,2,4b,y7
Group 2, Capture 1: 0
Group 2, Capture 2: 2
Group 2, Capture 3: 4b
Group 2, Capture 4: y7
有什么特别的原因,你*必须*使用正则表达式? – Amber 2010-04-16 09:49:57
问题看起来似乎比较容易一看,因为答案确实使用字符串操作。如果可能的话,我正在寻找另一种方法来解决我的问题与正则表达式方法。我必须使用正则表达式有一个特别的原因,因为除了使用字符串方法之外,我应该更加明确地了解RegEx。 – Myra 2010-04-16 12:52:50