-1

I have a string closed to square brackets:

[[oneOne1, oneOne2], oneTwo, oneThree]

I neet to extract substing that is closed to square brackets and get

[oneOne1, oneOne2], oneTwo, oneThree

I've tried to use regex. But the the hard part is that my substring also stores [ and ].

This is a string value of some variable that I receive. And it could be more than one occurrence in the string. I mean that string could also look like:

[[oneOne1, oneOne2], oneTwo, oneThree][[twoOne1, twoOne2], twoTwo, twoThree][[threeOne1, threeOne2], threeTwo, threeThree]

and I should extract all occurances:

[oneOne1, oneOne2], oneTwo, oneThree

[twoOne1, twoOne2], twoTwo, twoThree

[threeOne1, threeOne2], threeTwo, threeThree

There is a lot of such questions here but I didn't find solution for my case with internal []. Here I found solution for PHP PCRE, but I can't convert it to java 8.

How can I do this?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Igor_M
  • 308
  • 2
  • 12

1 Answers1

1

If there are no more than two levels of nested square brackets:

(?<=\[)(?:[^\[\]]+|\[[^\[\]]+\])+

see here for the online demo.


  • (?<=): Positive lookbehind
    • \[: Matches [.
  • (?:): Non capturing group.
    • [^\[\]]+: Matches any character other than [ or ], between one and unlimited times, as much as possible.
    • |: Or.
    • \[[^\[\]]+\]: Matches [, matches any character other than [ or ], between one and unlimited times, matches ].
  • +: Matches the preceding group between one and unlimited times, as much as possible.
Cubix48
  • 2,607
  • 2
  • 5
  • 17