in reply to Matching parens on a regex is beating me

You may be able to use this code in your solution. It finds nested brackets in strings but the match fails if the brackets aren't balanced. The bracket groups are shown in depth first, left to right order.

use strict; use warnings; use re q{eval}; my @codeStrings = ( q{func2(func1(input1, input2), input3)}, q{func1(input1, func2(input2, input3))}, q{Contains i(mbalan(ced Br(ack)ets, )one op)en m)missing}, q{So(me m(ultip)le n(est(s in) thi)s o)ne}, ); my @memoList; my $rxNest; $rxNest = qr {(?x) ( \( [^()]* (?: (??{$rxNest}) [^()]* )* \) ) (?{ [ @{$^R}, $^N ] }) }; my $rxOnlyNested; { $rxOnlyNested = qr {(?x) (?{ [] }) ^ [^()]* (?: $rxNest [^()]* )+ \z (?{ @memoList = @{$^R} }) }; } testString($_) for @codeStrings; sub testString { my $string = shift; @memoList = (); print qq{\nString: $string\n}; if($string =~ /$rxOnlyNested/) { print qq{ Match succeeded\n}; print qq{ ---------------\n}; print qq{ Before brackets:-\n}; print qq{ -->@{[substr $string, 0, $-[1]]}<--\n}; print qq{ Bracket pairs:-\n}; print qq{ $_\n} for @memoList; print qq{ After brackets:-\n}; print qq{ -->@{[substr $string, $+[1]]}<--\n}; } else { print qq{ Match failed\n}; } }

The output.

String: func2(func1(input1, input2), input3) Match succeeded --------------- Before brackets:- -->func2<-- Bracket pairs:- (input1, input2) (func1(input1, input2), input3) After brackets:- --><-- String: func1(input1, func2(input2, input3)) Match succeeded --------------- Before brackets:- -->func1<-- Bracket pairs:- (input2, input3) (input1, func2(input2, input3)) After brackets:- --><-- String: Contains i(mbalan(ced Br(ack)ets, )one op)en m)missing Match failed String: So(me m(ultip)le n(est(s in) thi)s o)ne Match succeeded --------------- Before brackets:- -->So<-- Bracket pairs:- (ultip) (s in) (est(s in) thi) (me m(ultip)le n(est(s in) thi)s o) After brackets:- -->ne<--

I hope this helps you.

Cheers,

JohnGG

Update: I've found the post this originally came from, diotalevi, ikegami and hv gave me lots of help in finding this solution.