my $op = qr/AND|OR|NOT/; my $block = qr/($op?)\s*\((\w\s+$op\s+\w)\)/; if ($str =~ m/^\(\s*(?:$block\s*)\)/){ # access $1, $2, ... here }