regexparenthesesopenrefinegrel

Remove outermost parentheses


I am having problem while removing outermost parentheses from a string using GREL. What i am trying to do is simply remove outermost parentheses and all other parentheses should be kept intact. Below is what i am trying to do using regex -

value.split(/(abc+/)

and below is my sample string that i am trying to parse and desired output.

Foo ( test1 test2 ) => Foo test1 test2
Bar ( test1 t3() test2 ) => Bar test1 t3() test2
Baz ((("Fdsfds"))) => Baz (("Fdsfds"))

I would appreciate any help.


Solution

  • One option could be to use a capturing group and in the replacement use the first capturing group.

    Note that this does not take balanced parenthesis into account.

    It matches the outer parenthesis, then captures in a group what is inside and matches an outer parenthesis again.

    Inside the capturing group is an alternation that matches not () or from an openening till closing parenthesis.

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

    Explanation

    Regex demo