我想在逗号(,)上用java分割一个字符串但是只要逗号(,)在某个括号之间,就不应该拆分它。
e.g。字符串:
"life, would, (last , if ), all"
应该屈服:
-life
-would
-(last , if )
-all
当我使用时:
String text = "life, would, (last , if ), all"
text.split(",");
我最终将整个文本划分为(最后,如果)我可以看到拆分需要一个正则表达式,但我似乎无法想到如何使它完成这项工作。
答案 0 :(得分:7)
您可以使用此模式 - (不适用于嵌套括号)
,(?![^()]*\))
, # ","
(?! # Negative Look-Ahead
[^()] # Character not in [()] Character Class
* # (zero or more)(greedy)
\ #
) # End of Negative Look-Ahead
)