我有这些示例类型的字符串:
"System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
"System.Collections.IEnumerable"
"System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Type, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
"Whatever`3[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[ImaginaryType],[System.Type, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
使用正则表达式,我想提取main-type,其泛型类型计数以及所有泛型类型本身,因此对于上面的四个示例,我相应地“捕获”了这些元素:
"System.Collections.Generic.IEnumerable"
1
"System.String"
"System.Collections.IEnumerable"
0
"System.Collections.Generic.Dictionary"
2
"System.Int32"
"System.Type"
"Whatever"
3
"System.Int32"
"ImaginaryType"
"System.Type"
有没有可以做到这一点的正则表达式?
您可以使用以下模式进行操作:
string pattern = @"
(?: # two possible entry points
\G(?!\A) # contigous to the precedent match
| # OR
\A # at the start of the string
(?<main> [^`]+ ) ` (?<number> [0-9]+ ) \[
)
\[ (?<type> [^],]+ ) # generic type
[^]]* ] # all until the next closing square bracket
(?: , | ]\z )
| \A (?<main> [^`]+ ) # or a main-type without generic types
";
RegexOptions options = RegexOptions.IgnorePatternWhitespace;
foreach (Match match in Regex.Matches(input, pattern, options)) { ...
如果您计划多次使用该模式,则最好一劳永逸地进行编译。请注意,您可以改用以下变体来减少正则表达式引擎的工作:
string pattern = @"
\G(?!\A) \[
(?<type> [^],]+ )
[^]]* ] (?: , | ]\z )
|
\A
(?<main> [^`]+ )
(?:
` (?<number> [0-9]+ )
\[{2}
(?<type> [^],]+ )
[^]]* ]
(?: , | ]\z )
|
\z
)";
如果要确保已到达字符串的末尾,则可以替换]\z
为(?<endcheck>]\z)
并控制该组是否存在于最后一个匹配项中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句