如何使用regex获取嵌套在另一个组中的重复组

本文关键字:另一个 何使用 regex 获取 嵌套 | 更新日期: 2023-09-27 18:25:44

我有以下示例类型的字符串:

"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]]"

使用regex,我想提取主类型、它的泛型类型计数以及所有泛型类型本身,因此对于上面的四个示例,我相应地"捕获"了这些元素:

"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"

有正则表达式可以做到这一点吗?

如何使用regex获取嵌套在另一个组中的重复组

您可以使用以下模式:

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),并控制组是否存在于最后一个匹配中。

相关文章: