#! use Smart::Comments; use strict; use warnings; my $np; $np=qr/ (?:\( # Capture the opening "(" (?: # '(?:[^']|\')*?' #' a single quote string |"(?:[^']|\")*?" #" a double quote string | [^()] # not a parentheses | (??{$np}) )* \)) # and the closing ")" /ix; my $string; my $re; $string=<<'__EOString__'; SELECT "SELECT * FROM table1 WHERE ...",'FROM WHERE' SQL FROM table2 join(select from here to where eternity) WHERE ... __EOString__ $re=qr/ ^([^'"(]* (?:"(?:[^']|\")*?"|'(?:[^']|\')*?'|$np)? )* [^'"(]* (\bFROM\b ([^'"(]* (?:"(?:[^']|\")*?"|'(?:[^']|\')*?'|$np)? )* [^'"(]*? \bWHERE\b) /ix; # works ### $string while ($string =~ m{$re}ig) { ### @- ### @+ ### $1 ### $2 ### $3 }; exit; #### ### $string: ' SELECT "SELECT * FROM table1 WHERE ..." "FROM WHERE"SQL FROM table2 join(select my mother from here to where eternity) WHERE ...' Complex regular subexpression recursion limit (32766) exceeded at RE.pl line 45. ### @-: '0', ### '64', ### '64', ### '127' ### @+: '132', ### '64', ### '132', ### '127' ### $1: '' ### $2: 'FROM table2 join(select my mother from here to where eternity) WHERE' ### $3: ''