将一个字符串按照子字符串进行分割,但括号内容不参与分割。

4

我们如何用 “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)

尝试了不同的正则表达式选项,但没有运气。

2
这看起来像是一个xy问题。那么x是什么?你是在尝试解析表达式另一个问题)吗? - Sinatr
你可以使用正则表达式 (?!<\(.*) and 进行分割,参考负向零宽断言(你也可以用负向顺序零宽断言实现同样的效果)。 - Андрей Саяпин
@Sinatr,我不是在尝试解析任何表达式,我只需要将它们拆分并呈现在列表中,只需要处理括号内的拆分。 - Baj B
@jdweng,我没有任何算术运算要执行,只是将字符串按“and”拆分,但排除括号内的“and”。 - Baj B
@АндрейСаяпин,尝试使用(?!<\(.*) ,但显示未识别的转义序列。 - Baj B
显示剩余2条评论
1个回答

5

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

\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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接