MATLAB: How to match nested parenthesis (brackets, or braces) with dynamic regular expressions

dynamic regular expressionsMATLABnested bracesnested bracketsnested parenthesis

One can read all over the web how it is impossible to use regular expressions to match nexted parenthesis. However MATLAB has this cool feature called 'dynamic regular expressions' that allow one to insert some MATLAB code to do all kinds of special 'gymnastics'. Is there a way to use this feature to count instances of parenthesis and, in turn, find their matches? Consider the following string:
g = 'asdf (( dwer e: ( asdedsdskek))::)asd fg ( qwe 4 dfy5 57) q34 dqa5';
or
g = 'asdf (( (dwer ) e: ( asdedsdskek))::)asd fg ( qwe 4 dfy5 57) q34 dqa5';
or
g = 'asdf ( dwer e: )asd fg ( qwe 4 dfy5 57) q34 dqa5';
Specifically, my need is only to match the first left parenthesis with its partner but one would think the more general solution of matching all sets of parenthesis is feasible with dynamic regular expressions. If anyone can help with this, it would be much appreciated.

Best Answer

This matches the outer-most matched pair of parentheses:
>> str = 'asdf (( dwer e: ( asdedsdskek))::)asd fg ( qwe 4 dfy5 57) q34 dqa5';
>> fun = @(s)sprintf('.{%d}',find(cumsum((s==')' )-(s=='('))>0,1,'first'));
>> out = regexp(str,'\((??@fun($''))','match')
out =
'(( dwer e: ( asdedsdskek))::)' '( qwe 4 dfy5 57)'