2014-05-13 31 views
0

爲什麼正則表達式正則表達式捕獲組覆蓋前面的比賽

class (?<class>\w+) (?<b>\{)(?:\s*(?<method>\w+)\(\)\{\})*\s*(?<-b>\}) 
當應用於

class A { B(){} C(){} } 

只返回

class: A 
method: C 

在我看來,它應該也匹配B.

有沒有辦法實現這一點?

回答

0

如果您有重複的羣組,您必須使用捕獲。

Match m = Regex.Match("class A { B(){} C(){} }", @"class (?<class>\w+) (?<b>\{)(?:\s*(?<method>\w+)\(\)\{\})*\s*(?<-b>\})"); 
var methods = m.Groups["method"].Captures; 
for (int i = 0; i < methods.Count; i++) 
    Console.WriteLine(methods[i].Value); 

輸出:

B 
C 

C# Demo

另外:不能使用-b爲組名,將其更改爲b_end或類似的,否則你將無法捕獲b-b組。

class (?<class>\w+) (?<b_start>\{)(?:\s*(?<method>\w+)\(\)\{\})*\s*(?<b_end>\}) 

Regular expression visualization

+0

其實我並不想捕捉B和-b,我只是想用它們來匹配括號。 – chrischu