Java 在逗号 (,) 上拆分字符串,括号 () 之间除外

Java split string on comma(,) except when between parenthesis ()

我想在 java 中用逗号 (,) 拆分字符串,但是只要逗号 (,) 位于某些括号之间,就不应拆分。

例如字符串:

"life, would, (last , if ), all"

应该产生:

-life
-would
-(last , if )
-all

当我使用时:

String text = "life, would, (last , if ), all"
text.split(",");

我最终将整个文本甚至 (last , if ) 都分开了我可以看到拆分需要一个正则表达式,但我似乎想不出如何让它完成这项工作。

您可以使用此模式 -(不适用于嵌套括号)

,(?![^()]*\))

Demo

,               # ","
(?!             # Negative Look-Ahead
  [^()]         # Character not in [()] Character Class
  *             # (zero or more)(greedy)
  \             # 
)               # End of Negative Look-Ahead
)