my $bal = # this is from perlre qr/ \( (?: (?> [^()]+ ) | (??{$bal}) )* \) /x; $text =~ s/ ( (?: (??{$bal}) [^(\d]* )* ) (\d+) (?= \) ) /$1\n$2/xg;