0
爲什麼正則表達式正則表達式捕獲組覆蓋前面的比賽
class (?<class>\w+) (?<b>\{)(?:\s*(?<method>\w+)\(\)\{\})*\s*(?<-b>\})
當應用於
class A { B(){} C(){} }
只返回
class: A
method: C
?
在我看來,它應該也匹配B.
有沒有辦法實現這一點?
爲什麼正則表達式正則表達式捕獲組覆蓋前面的比賽
class (?<class>\w+) (?<b>\{)(?:\s*(?<method>\w+)\(\)\{\})*\s*(?<-b>\})
當應用於
class A { B(){} C(){} }
只返回
class: A
method: C
?
在我看來,它應該也匹配B.
有沒有辦法實現這一點?
如果您有重複的羣組,您必須使用捕獲。
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
另外:不能使用-b
爲組名,將其更改爲b_end
或類似的,否則你將無法捕獲b
和-b
組。
class (?<class>\w+) (?<b_start>\{)(?:\s*(?<method>\w+)\(\)\{\})*\s*(?<b_end>\})
其實我並不想捕捉B和-b,我只是想用它們來匹配括號。 – chrischu