Search code examples
javascriptregexcurly-braces

Regex for getting string in outer curly braces containing multiple inner curly braces


i need to find the regex to give me a string in curly braces, where the string also contains curly braces. This is the string is like

input{
    stdin {
     type => "stdin-type"
       }
    file {
     type => "file"
      }
}

output {
      stdout { }
}

What i want is for example just the input part. My latest try was:

input{([\s\S]*)\n}

This works, when there is only one inner pair of curly braces and a newline before the last curly brace, but that might not always be the case. And there may be even more inner elements with curly braces. So i need something more flexible. Something with an open counter or alike.

And i need it for javascript.

Perhaps it is not makeable with regex??

Ideas welcome.

tmoe


Solution

  • Having logic in regex to match nested patterns might bring you into a nightmare and regex may not be the right tool for this.

    Basing on your regex, I can come up with some changes and using this one:

    input{([\s\S]*?)^}
    

    Working demo

    It will use the start line with } as the end delimiter which could solve your specific problem, however regex may not be the best answer for your problem.