b and b = 0 and (f = 1 and g = 2)"做,field.Split(" and ")将返回 4 个字符串,其中我们-6ren">
gpt4 book ai didi

c# - 用除括号外的子字符串分割字符串

转载 作者:行者123 更新时间:2023-12-03 21:45:05 25 4
gpt4 key购买 nike

我们如何用“和”分割后面的内容。field = "a > b and b = 0 and (f = 1 and g = 2)"做,field.Split(" and ")将返回 4 个字符串,其中我们将在其中包含括号

a > b
b = 0
(f = 1
g = 2)
我只想要 3 个字符串,由外部 "and"拆分:
a > b
b = 0
(f = 1 and g = 2)
也尝试了各种 Regex 选项,但没有运气。

最佳答案

即使您有嵌套的平衡括号,您也可以使用

\s*\band\b\s* # whole word and enclosed with 0+ whitespaces
(?= # start of a positive lookahead:
(?:
[^()]* # 0 or more chars other than ( and )
\((?>[^()]+|(?<o>\()|(?<-o>\)))*(?(o)(?!))\) # a (...) substring with nested parens support
)* # repeat the sequence of above two patterns 0 or more times
[^()]*$ # 0 or more chars other than ( and ) and end of string
) # end of the positive lookahead
regex demo .
C# snippet :
var text = "a > b and b = 0 and (f = 1 and (g = 2 and j = 68) and v = 566) and a > b and b = 0 and (f = 1 and g = 2)";
var pattern = @"(?x)
var pattern = @"(?x)
\s*\band\b\s* # whole word and enclosed with 0+ whitespaces
(?= # start of a positive lookahead:
(?:
[^()]* # 0 or more chars other than ( and )
\((?>[^()]+|(?<o>\()|(?<-o>\)))*(?(o)(?!))\) # a (...) substring with nested parens support
)* # repeat the sequence of above two patterns 0 or more times
[^()]*$ # 0 or more chars other than ( and ) and end of string
) # end of the positive lookahead";
var results = Regex.Split(text, pattern);
输出:
a > b
b = 0
(f = 1 and (g = 2 and j = 68) and v = 566)
a > b
b = 0
(f = 1 and g = 2)

关于c# - 用除括号外的子字符串分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64893312/

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