I'm searching for a regex to match all C# methods in a text and the body of each found method (refrenced as "Content") should be accessible via a group.
The C# Regex above only gives the desired result if there exists exactly ONE method in the text.
Source text:
void method1(){
if(a){ exec2(); }
else { exec3(); }
}
void method2(){
if(a){ exec4(); }
else { exec5(); }
}
The regex:
string pattern = "(?:[^{}]|(?<Open>{)|(?<Content-Open>}))+(?(Open)(?!))";
MatchCollection methods = Regex.Matches(source,pattern,RegexOptions.Multiline);
foreach (Match c in methods)
{
string body = c.Groups["Content"].Value; // = if(a){ exec2(); }else { exec3();}
//Edit: get the method name
Match mDef= Regex.Match(c.Value,"void ([\\w]+)");
string name = mDef.Groups[1].Captures[0].Value;
}
If only the method1 is contained in source, it works perfectly, but with additional method2 there is only one Match, and you cannot extract the individual method-body pairs any more.
How to modify the regex to match multiple methods ?