正则表达式:匹配多个平衡组
Regex: Match multiple balancing groups
我正在寻找一个正则表达式来匹配文本中的所有 C# 方法,每个找到的方法的主体(引用为 "Content")应该可以通过组访问。
如果文本中恰好存在一种方法,则上面的 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_name>\w+)\s*\((?s:.*?)\)\s*(?<method_body>\{(?>[^{}]+|\{(?<n>)|}(?<-n>))*(?(n)(?!))})
见demo
要访问您需要的值,请使用 .Groups["method_name"].Value
和 .Groups["method_body"].Value
。
我正在寻找一个正则表达式来匹配文本中的所有 C# 方法,每个找到的方法的主体(引用为 "Content")应该可以通过组访问。
如果文本中恰好存在一种方法,则上面的 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_name>\w+)\s*\((?s:.*?)\)\s*(?<method_body>\{(?>[^{}]+|\{(?<n>)|}(?<-n>))*(?(n)(?!))})
见demo
要访问您需要的值,请使用 .Groups["method_name"].Value
和 .Groups["method_body"].Value
。