0

I am trying to construct a regex that will return true to a set of multiple square brackets, as long as they are opened and closed correctly.

For e.g.

[1][2][3] - true
[1][2][3][4][5] - true
[[1,2],[2]] - true

I got this one but am able to do it for only 3 : "\[([^\]]+)\]\[([^\]]+)\]\[([^\]]+)\]"

Any help appreciated.

user1722908
  • 535
  • 2
  • 9
  • 21
  • 3
    Java regex does not support recursion. You may use a regex for a 1 or 2 nested levels, but then it becomes unwieldly. – Wiktor Stribiżew Jun 13 '17 at 19:34
  • Just use counter. Increment it when you found `[` decrement when you found `]`. If counter ever goes negative there is a problem. If counter at the end is different than `0` there is also a problem. – Pshemo Jun 13 '17 at 19:37
  • This post might have some useful information... https://stackoverflow.com/questions/3826395/parse-string-into-a-tree-structure – Steve Jun 13 '17 at 19:40
  • Proper answer is that it can't be done with regex in Java. To get idea of possible solution take a look at duplicate question. – Pshemo Jun 13 '17 at 19:45

0 Answers0