【问题标题】:Split a string by a substring except for brackets用除括号外的子字符串拆分字符串
【发布时间】:2020-11-18 12:39:06
【问题描述】:

我们怎样才能用“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)

我只想要 3 个字符串,由外部“和”分割:

a > b
b = 0
(f = 1 and g = 2)

也尝试了各种正则表达式选项,但没有成功。

【问题讨论】:

  • 这看起来像xy problem。 x是什么?你想parse expression (another question) 吗?
  • 你可以通过正则表达式(?!<\(.*) and 进行拆分,查看负向lookbehind(你可以用同样的方式使用负向lookahead)
  • 你不能通过拆分你做的方式来解析。您在加法/减法之前失去了乘法/除法等术语的优先级。
  • @Sinatr,我不是要解析任何表达式,我只需要将它们拆分并呈现在列表中,只需要处理括号中的拆分
  • @jdweng,我没有任何算术运算来执行仅用“and”分割字符串,括号内的“and”除外

标签: c# regex


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-11-17
    • 2020-07-03
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2021-01-19
    相关资源
    最近更新 更多