如何获得嵌套的括号内的文字? [英] How to get text between nested parentheses?
本文介绍了如何获得嵌套的括号内的文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
获取括号()之间的文本表达注册,我试过,但我没有得到的正则表达式。在这个例子中
Regex.Match(脚本,@\((。*?)\))。值
例如: -
添加(MUL(一,加(b,C)),D)+ E - 子(F,G)
输出=>
1)MUL(A,加入(B,C)),D
2)F,G
解决方案
.NET允许的递归的正则表达式。请参见均衡组定义
<预类=郎-CS prettyprint-覆盖>
VAR输入= @添加(MUL(A,加入(b,C)),D)+ E - 子(F,G);
变种的regex =新的正则表达式(@
\(#匹配(
(
[^()] +#除非所有字符()$ B $ C |(?<平> \()#如果(当时等级+ = 1
|(小于?-Level> \))#如果),那么级别 - = 1
)+#重复(从内到外)
(?(级)(?!))#零宽度负预测先行断言
\)#匹配),
RegexOptions .IgnorePatternWhitespace);
的foreach(匹配C的在regex.Matches(输入))
{
Console.WriteLine(c.Value.Trim('('')'));
}
Reg Expression for Getting Text Between parenthesis ( ), I had tried but i am not getting the RegEx. For this example
Regex.Match(script, @"\((.*?)\)").Value
Example:-
add(mul(a,add(b,c)),d) + e - sub(f,g)
Output =>
1) mul(a,add(b,c)),d
2) f,g
解决方案
.NET allows recursion in regular expressions. See Balancing Group Definitions
var input = @"add(mul(a,add(b,c)),d) + e - sub(f,g)";
var regex = new Regex(@"
\( # Match (
(
[^()]+ # all chars except ()
| (?<Level>\() # or if ( then Level += 1
| (?<-Level>\)) # or if ) then Level -= 1
)+ # Repeat (to go from inside to outside)
(?(Level)(?!)) # zero-width negative lookahead assertion
\) # Match )",
RegexOptions.IgnorePatternWhitespace);
foreach (Match c in regex.Matches(input))
{
Console.WriteLine(c.Value.Trim('(', ')'));
}
这篇关于如何获得嵌套的括号内的文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文