[英]Regex: Match multiple balancing groups
我正在尋找一個正則表達式以匹配文本中的所有C#方法,並且應該可以通過組訪問每個找到的方法的主體(簡稱為“內容”)。
如果文本中僅存在一個方法,則上面的C#正則表達式只能提供所需的結果。
源文本:
void method1(){
if(a){ exec2(); }
else { exec3(); }
}
void method2(){
if(a){ exec4(); }
else { exec5(); }
}
正則表達式:
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;
}
如果源中僅包含method1,則它可以正常工作,但在其他method2中,只有一個Match,並且您無法再提取各個method-body對。
如何修改正則表達式以匹配多種方法?
假設您只想匹配問題中的示例之類的基本代碼,則可以使用
(?<method_name>\w+)\s*\((?s:.*?)\)\s*(?<method_body>\{(?>[^{}]+|\{(?<n>)|}(?<-n>))*(?(n)(?!))})
觀看演示
要訪問所需的值,請使用.Groups["method_name"].Value
和.Groups["method_body"].Value
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.