正则表达式匹配成功,如何在遍历所有捕获组时取得组名?
本帖最后由 u010936098 于 2013-06-28 09:31:20 编辑 有这样一段代码:
Regex testXpress = new Regex(
@"^\s*(?:" +
@"(?:" +
@"(?:(?<low_bound>\d+(?:\.\d+)?))" +
@"\s*(?:-|~)\s*" +
@"(?:(?<high_bound>\d+(?:\.\d+)?))" +
")" +//0.78 - 1.23; 1-2.24; 4.3 -6; 5-9
@"|(?:(?:≤|(?:<=))\s*(?<high_bound>\d+(?:\.\d+)?))" + //<= 1.23; ≤1.12; <=1; ≤ 2
@"|(?:(?:≥|(?:>=))\s*(?<low_bound>\d+(?:\.\d+)?))" + //>= 1.23; ≥1.12; >=1; ≥ 2
@"|(?:(?:<|<)\s*(?<high_bound>\d+(?:\.\d+)?))" + //< 1.23; <1.12; <1; < 2
@"|(?:(?:>|>)\s*(?<low_bound>\d+(?:\.\d+)?))" + //> 1.23; >1.12; >1; > 2
@"|(?<accurate>\d+(?:\.\d+)?)" + // 12.45; 36
@")\s*$"
);
Match mc = testXpress.Match(textBox1.Text);
if (mc.Success)
{
foreach (Group gp in mc.Groups)
{
//string name = ?这里怎么获得捕获组的名字》?
foreach (Capture cp in gp.Captures)
{
//do something with name and cp.value
}
}
}
正则表达式匹配成功后,要遍历gropus中的group,并根据组名对捕获结果进行处理。
上面给出的正则表达式只是其中最简单的一个。
正则表达式 RegEx 捕获组
[解决办法]
it is also easy:
GroupCollection groups = regex.Match(line).Groups;
foreach (string groupName in regex.GetGroupNames())
{
Console.WriteLine(
"Group: {0}, Value: {1}",
groupName,
groups[groupName].Value);
}