簡體   English   中英

用除括號外的子字符串分割字符串

[英]Split a string by a substring except for brackets

我們如何用“和”分割后面的內容。

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

請參閱正則表達式演示

查看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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM