2014-10-07 18 views
1

我的這些實施例一類型的字符串:如何獲得嵌套在正則表達式中的重複組?

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

使用正則表達式,我想提取的主要類型,它的泛型類型計數,和所有的通用類型本身,所以上面的四個例子,我「趕「這些元素相應地:

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

是否有正則表達式可以做到這一點?

+0

是的。您可以使用嵌套組,如下所示:'^(first-group-expression(second-group-expression))$'。 – 2014-10-07 11:06:39

回答

2

你可以用這種模式做到這一點:

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

如果你想確保字符串的結尾已經達到可以與(?<endcheck>]\z)和控制,如果該組中存在替代]\z最後的比賽。

+0

哇!很好的回答:-)但它仍然錯過了最後一個例子:''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]]'' - (由於SO的解析,改變了撇號的反標),它停在第二種類型 - 'ImaginaryType'上,因爲它不會在任何逗號前面... – Tar 2014-10-07 12:55:40

+0

阿格,我一直在這裏出汗已經有一段時間了,這個Dynamic Duo把它從公園裏敲出來。試圖抓住Tal的第三種情況:) – samy 2014-10-07 13:17:19

+0

@Tal:你只需要在否定的字符類中添加方括號即可,請參閱我的編輯。 – 2014-10-07 13:44:15