Home > Enterprise >  Regex to match everything inside brackets ignore nested
Regex to match everything inside brackets ignore nested

Time:04-07

I am looking for a regex rule to match everything inside square brackets, including the brackets and ignoring the possible brackets inside. E.g. from:

[value] in the [text[42]] and [1[2[3]]]!

I need to extract [value], [text[42]] and [1[2[3]]].

I use

\[(.*?)\]

Here are more expamples - https://regex101.com/r/Xp4ghi/1

P.S. I am going to use it in .NET

CodePudding user response:

You can use

\[(?>[^][] |(?<c>)\[|(?<-c>)]) ]

See the regex demo. Details:

  • \[ - a [ char
  • (?>[^][] |(?<c>)\[|(?<-c>)]) - one or more occurrences of
    • [^][] | - one or more chars other than ] and [, or
    • (?<c>)\[| - a [ char and a value is pushed onto Group "c" stack, or
    • (?<-c>)] - a ] char and a value is popped off the Group "c" stack
  • ] - a ] char.
  • Related