有没有办法在 C# 中获取捕获组的名称?
string line = "No.123456789 04/09/2009 999";
Regex regex = new Regex(@"(?<number>[\d]{9}) (?<date>[\d]{2}/[\d]{2}/[\d]{4}) (?<code>.*)");
GroupCollection groups = regex.Match(line).Groups;
foreach (Group group in groups)
{
Console.WriteLine("Group: {0}, Value: {1}", ???, group.Value);
}
我想得到这个结果:
Group: [I don´t know what should go here], Value: 123456789 04/09/2009 999
Group: number, Value: 123456789
Group: date, Value: 04/09/2009
Group: code, Value: 999
Use 获取组名 http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.getgroupnames.aspx获取表达式中的组列表,然后使用名称作为组集合的键来迭代这些组。
例如,
GroupCollection groups = regex.Match(line).Groups;
foreach (string groupName in regex.GetGroupNames())
{
Console.WriteLine(
"Group: {0}, Value: {1}",
groupName,
groups[groupName].Value);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)