Regex 正则表达式能否替换表达式访问命名组中的多个捕获?

Regex 正则表达式能否替换表达式访问命名组中的多个捕获?,regex,replace,Regex,Replace,我正在尝试编写一个正则表达式替换表达式,用它的C#等价物替换完全限定的泛型类型名。例如,以下文本: System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyNamespace.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral,

我正在尝试编写一个正则表达式替换表达式,用它的C#等价物替换完全限定的泛型类型名。例如,以下文本:

System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyNamespace.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
将成为以下C#类型名称:

System.Collections.Generic.Dictionary<System.String, MyNamespace.MyClass>
System.Collections.Generic.Dictionary
无论泛型类型中有多少类型参数,我的正则表达式都需要工作。我编写了一个表达式,它成功地将泛型类型及其类型参数捕获到两个命名组中:

^(?<GenericType>.+)`\d\[(?:\[?(?<GenericTypeParam>\S*),[^\]]+\]?,?)+\]$
^(?.+)`\d\[(?:\[?(?\S*),[^\]+\],?)+\]$
现在我需要编写生成C#类型名称的替换表达式。但由于“GenericTypeParam”组中可能有多个捕获,因此我需要能够在替换表达式中引用可变数量的捕获。下面是我现在使用的替换表达式:

${GenericType}<${GenericTypeParam}>
${GenericType}
但由于它按名称引用“GenericTypeParam”组,因此它获取组值,即组中最后一次捕获的值。因此,此替换表达式的输出为:

System.Collections.Generic.Dictionary<MyNamespace.MyClass>
System.Collections.Generic.Dictionary

因此,我的输出字符串只包含组中的最后一个捕获有没有办法访问replace表达式中的其他捕获?

我认为使用regex replace无法做到这一点。我认为您必须通过编程循环匹配,而不是使用替换表达式提取它们。比如(未经测试!):

列表类型=新列表();
匹配m;
for(m=reg.Match(GenericTypeParam);m.Success;m=m.NextMatch()){
添加(m.Groups[“GenericTypeParam”].Value);
}
然后将列表连接到泛型类型param中

List<string> types = new List<string>();
Match m;
for (m = reg.Match(GenericTypeParam); m.Success; m = m.NextMatch()) {
    types.Add( m.Groups["GenericTypeParam"].Value ); 
}