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

空扰寡人 提交于 2019-12-07 05:30:11

问题


I would like to split a string in java on a comma(,) but whenever the comma(,) is in between some parenthesis, it should not be split.

e.g. The string :

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

Should yield:

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

When I use :

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

I end up dividing the whole text even the (last , if ) I can see that split takes a regex but I can't seem to think of how to make it do the job.


回答1:


you could use this pattern - (not for nested parenthesis)

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

Demo

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


来源:https://stackoverflow.com/questions/31993153/java-split-string-on-comma-except-when-between-parenthesis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!