简体   繁体   English

正则表达式:匹配多个平衡组

[英]Regex: Match multiple balancing groups

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. 我正在寻找一个正则表达式以匹配文本中的所有C#方法,并且应该可以通过组访问每个找到的方法的主体(简称为“内容”)。

The C# Regex above only gives the desired result if there exists exactly ONE method in the text. 如果文本中仅存在一个方法,则上面的C#正则表达式只能提供所需的结果。

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. 如果源中仅包含method1,则它可以正常工作,但在其他method2中,只有一个Match,并且您无法再提取各个method-body对。

How to modify the regex to match multiple methods ? 如何修改正则表达式以匹配多种方法?

Assuming you only want to match basic code like those samples in your question, you can use 假设您只想匹配问题中的示例之类的基本代码,则可以使用

(?<method_name>\w+)\s*\((?s:.*?)\)\s*(?<method_body>\{(?>[^{}]+|\{(?<n>)|}(?<-n>))*(?(n)(?!))})

See demo 观看演示

在此处输入图片说明

To access the values you need, use .Groups["method_name"].Value and .Groups["method_body"].Value . 要访问所需的值,请使用.Groups["method_name"].Value.Groups["method_body"].Value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM