use strict; use warnings; no warnings qw /uninitialized/; # \A anchor removed, so this is the same regex from the perlfaq. my $re; $re = qr{ \( (?: (?> [^()]+ ) # Non-parens without backtracking | (??{ $re }) # Group with matching parens )* \) }x; while () { chomp; print "$_: "; # here is the proper place for the anchor print $& if /\A$re/; print "\n"; } __DATA__ (*********) (***(*)***) ((***)) (((***))) ((**)**(**)) (((())))