Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 670
Bwire Avatar asked Aug 13 '15 15:08

Bwire


1 Answers

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
)
like image 175
alpha bravo Avatar answered Oct 13 '22 17:10

alpha bravo