我们如何用 “and” 分割以下内容。
field = "a > b and b = 0 and (f = 1 and g = 2)"
执行 field.Split(" and ")
将返回 4 个字符串,其中它们内部将有括号。
a > b
b = 0
(f = 1
g = 2)
我只需要通过外部的 "and" 分割成 3 个字符串:
a > b
b = 0
(f = 1 and g = 2)
尝试了不同的正则表达式选项,但没有运气。
即使您拥有嵌套平衡的括号,也可以使用
\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
查看正则表达式演示。
参见C#片段:
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)
(?!<\(.*) and
进行分割,参考负向零宽断言(你也可以用负向顺序零宽断言实现同样的效果)。 - Андрей Саяпин(?!<\(.*)
和