#/usr/bin/perl use strict; use warnings; my $string = 'NOT ("test(s)"[MESH] AND ("A"[MESH] OR "B"[MESH]))'; my $parens_guts; # Can't combine this line with the next one. $parens_guts = qr/ (?: "[^"]*" | \( (??{ $parens_guts }) \) | [^"()] )* /sx; $string =~ s/ \s* NOT \s* (?: "[^"]*"\[MESH\] | \( (??{ $parens_guts }) \) ) //gsx; print("[$string]$/");