use strict; our $regex = qr /( # Start capture \( # Start with '(', (?: # Followed by (?>[^()]+) # Non-parenthesis |(??{ $regex }) # Or a balanced () block )* # zero or more times \) # Close capture )/x; # Ending with ')' my $text = '(outer(inner(most inner)))'; $text =~ /$regex/gs; print "$1\n";