2

I have found some regex to match textblocks between brackets. However, what if I have some String with nested brackets and I only want the most external part of it.

eg. "foo bar [first [second] [third]] asdf ]]]]"

I would like to be able to match the text between the first opening bracket and it's closing bracket, leaving everything inside intact.

Result would be: "[first [second] [third]]"

melpomene
  • 79,257
  • 6
  • 70
  • 127
Martin
  • 2,894
  • 22
  • 37
  • It isn't possible in all language, what language do you use? – Casimir et Hippolyte Nov 08 '17 at 12:49
  • 1
    If recursion is supported: [**`\[(?:[^][]*|(?R))*\]`**](https://regex101.com/r/7heTQT/1/) – Jan Nov 08 '17 at 12:51
  • I use Java, if it wasn't supported, I would have to go for another approach... :) – Martin Nov 08 '17 at 12:51
  • Looking at this: https://stackoverflow.com/questions/12584124/how-to-match-nested-function-invocations-bracket-pairs-using-a-regular-express maybe the regex is the wrong approach? – Martin Nov 08 '17 at 12:57
  • [See the Java demo](https://ideone.com/hh6IBL), it now extracts multiple nested brackets. I also updated [my answer](https://stackoverflow.com/a/37207892/3832970). – Wiktor Stribiżew Nov 08 '17 at 13:09
  • @WiktorStribiżew, thank you for your answer. I was lookig for some "lazy" way where I could use existing code as a base. However, I ended up not parsing the string, but finding a way of getting the stuff I needed from Metadata since I was about to parse a String before having sent it through the network. Reason was that integration between different products is not always easy, but as I said, I found a way to pass the extra data in a Java Datastructure reliably... – Martin Nov 13 '17 at 08:26

1 Answers1

2

The classical recursion problem (if recursion is supported):

\[(?:[^][]*|(?R))*\]

See a demo on regex101.com.

Jan
  • 38,539
  • 8
  • 41
  • 69