我正在尝试编写一个正则表达式替换表达式,该表达式将使用其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>
无论泛型类型中的类型参数的数量如何,我的正则表达式都需要工作。我写了一个表达式,成功地将泛型类型及其类型参数捕获到两个命名组中:
^(?<GenericType>.+)`\d\[(?:\[?(?<GenericTypeParam>\S*),[^\]]+\]?,?)+\]$
现在我需要编写生成C#类型名称的replace表达式。但是因为“GenericTypeParam”组中可以有多个捕获,所以我需要能够在我的replace表达式中引用可变数量的捕获。这是我现在的替换表达式:
${GenericType}<${GenericTypeParam}>
但是因为它按名称引用了“GenericTypeParam”组,所以它获取组值,该值是组中最后一次捕获的值。所以,这个替换表达式的输出是:
System.Collections.Generic.Dictionary<MyNamespace.MyClass>
所以我的输出字符串只包含组中的最后一个捕获。 有没有办法访问替换表达式中的其他捕获?
答案 0 :(得分:0)
我认为你不能用正则表达式替换它。我认为你必须以编程方式循环遍历匹配,而不是用替换表达式提取它们。像(未经测试的!):
List<string> types = new List<string>();
Match m;
for (m = reg.Match(GenericTypeParam); m.Success; m = m.NextMatch()) {
types.Add( m.Groups["GenericTypeParam"].Value );
}
然后将列表连接到泛型类型参数。