-2

I'm trying to split a string in java based on brackets with the possibility that there are nested brackets, example:

"{one two {three}}{one {two} {{three}}}"

what I would like to get is an array with

array [0] = {one two {three}}

array [1] = {one {two} {{three}}}

I tried using the \ {(. *?) \} Regex but I get substrings like

{one two {Three}

which do not take into account which is the correct closing parenthesis

How can I do it?

2 Answers2

0

It is not possible to do this with a regex (alone), as you are trying to recognize a non-regular grammar. Just iterate over the string, while maintaining a counter representing the current nesting depth. Whenever you hit a right bracket and the depth goes down to zero, output the portion of the substring since the last time the depth hit zero.

Sneftel
  • 40,271
  • 12
  • 71
  • 104
-1

First try introducing a new line between consecutive right and left parentheses - that is - }[ ]*{. Then you can split on the new line ( may need to remove existing new lines before replacing if or as required ).

Ravindra HV
  • 2,558
  • 1
  • 17
  • 26
  • That doesn’t work with nested braces. Consider `{{one}{two}}`. And there’s no need for the newline stuff. – Sneftel Jun 26 '21 at 12:53
  • Idea was to answer for specific example. However even there it would have failed for `{two} {{three}}`. So in any case its not something that was doable. – Ravindra HV Jun 27 '21 at 22:08