如何在嵌套括号之间获取文本? [英] How to get text between nested parentheses?
本文介绍了如何在嵌套括号之间获取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用于在括号 ( ) 之间获取文本的 Reg 表达式,我已经尝试过,但我没有得到 RegEx.对于这个例子
Reg Expression for Getting Text Between parenthesis ( ), I had tried but i am not getting the RegEx. For this example
Regex.Match(script, @"((.*?))").Value
示例:-
add(mul(a,add(b,c)),d) + e - sub(f,g)
Output =>
1) mul(a,add(b,c)),d
2) f,g
推荐答案
.NET 允许在正则表达式中递归.请参阅平衡组定义
.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屋!
查看全文