while ($str =~ /\G(AND|OR)\s+(\(.+?\))/g) { printf("%s %s\n", $1, $2); }