我有一个 .NET 正则表达式,它看起来类似于:
(?<Type1>AAA)|(?<Type2>BBB)
我正在对示例字符串使用 Matches 方法,例如
"AAABBBAAA"
,然后遍历匹配项。我的目标是使用正则表达式匹配组找到匹配类型,因此对于此正则表达式,它将是:
我找不到任何
GetGroupName
方法。请帮忙。
最佳答案
这是你要找的东西吗?它使用 Regex.GroupNameFromNumber
所以你不需要知道正则表达式本身之外的组名。
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main()
{
Regex regex = new Regex("(?<Type1>AAA)|(?<Type2>BBB)");
foreach (Match match in regex.Matches("AAABBBAAA"))
{
Console.WriteLine("Next match:");
GroupCollection collection = match.Groups;
// Note that group 0 is always the whole match
for (int i = 1; i < collection.Count; i++)
{
Group group = collection[i];
string name = regex.GroupNameFromNumber(i);
Console.WriteLine("{0}: {1} {2}", name,
group.Success, group.Value);
}
}
}
}
关于.net - 正则表达式:如何获取组名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1163344/