Home > Enterprise >  How to split String var each coma only if not contained in brackets?
How to split String var each coma only if not contained in brackets?

Time:08-25

I have this String test = "elevation[value1,value2],temperature[value2,value3],radiance[value4,value5]..."

I would like to split each , not contained between square brackets. To get something like [ [elevation[value1,value2]] , [temperature[value2,value3]] , [radiance[value4,value5]] ]

I mean each element will be like elevation[value1,value2]

I am really not confortable using regex, if someone can help me.

CodePudding user response:

You can target each comma that is not contained within brackets using following regex but assuming your brackets will have to be balanced.

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

and split to get your desired results.

Demo

Link to Java code demo

Explanation:

  • , - Match a comma
  • (?![^\[]*\]) - This negative lookahead ensures that there is no ] character directly without an [ opening bracket.
  • Related