for ( A .. E ) { print "$_: "; print '((A, B), C, (D, E))' =~ match( $_ ); # Returns '(D, E)' print "\n"; } sub match { my $search = shift; my $re; eval qq[ \$re = qr/ \\( # Opening parenthese ((?: # Capture the contents [^()]+ # Body of a link | (??{\$re}) # Or recurse )+) # and allow repeats internally \\) # Closing parenthese # Test that the just-closed capture block contains $search. (?(?{ -1 != index \$^N, \$search })(?=)|(?!)) /x; ] or die $@; return $re; }