use strict; use warnings; my $str = 'I am (giving this (text to (tell you) that this) will give) you the result)))'; my $match = ''; { local $_ = $str; my $n = 0; s/([()]|.)/ if ($1 eq '(') { $n++; $match .= $1 } elsif ($1 eq ')') { if ($n) { $n--; $match .= $1 } } else { $match .= $1 if $n } /gex; } print "$match\n"; __END__ # output (giving this (text to (tell you) that this) will give)