Question

Why does the regex

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

when applied to

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

only return

class: A
method: C

?

In my opinion it should also match B.

Is there a way to achieve that?

Was it helpful?

Solution

You have to use captures if you have repeated groups.

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

Output:

B
C

C# Demo

Additionally: You cannot use -b as group name, change it to b_end or similar, otherwise you will not capture b and -b groups.

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

Regular expression visualization

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top