gpt4 book ai didi

c# - 如何获取嵌套括号之间的文本?

转载 作者:可可西里 更新时间:2023-11-01 07:50:17 25 4
gpt4 key购买 nike

用于在括号 ( ) 之间获取文本的正则表达式,我已经尝试过了,但我没有获得正则表达式。对于这个例子

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 允许正则表达式中的递归。参见 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('(', ')'));
}

关于c# - 如何获取嵌套括号之间的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19693622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com