Java splits the string into a comma (,), except between brackets ()

I would like to split a string in java into a comma (,), but whenever a comma (,) is between some brackets, it should not be separated.

eg. Line:

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

Must issue:

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

When i use:

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

I end up splitting all the text even into (the last one if), I see that split accepts a regular expression, but I can't imagine how to get it to do this work.

+4
source share
1 answer

you can use this pattern - (not for nested brackets)

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

Demo

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

All Articles