#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; my $string = '((()))(((())))(()(()))'; my $max = 0; my $depth = 0; if ($string =~ /^( \( (?{$max = $depth if ++$depth > $max}) (?1)* \) (?{--$depth}) ) (?1)* $/gx ) { say $max; }