use strict; use warnings; while () { chomp; while (m/(--.*?$) #that is comment | ((?:'[^']*'|[^'-]*)) #quated part of sql or ordinal part /xg) { #global, extended print $2 if $2; } print "\n"; } __DATA__ select 'text' from foo --This is a comment select '--Not a valid comment' from foo --But this is select q from z -- as is this select '--This is not a valid comment' from foo select '--Not this' + '--either' from foo select 'qaws' + make from "a" -- comment with 'a' quote select 'a' from 'b' with 'c' -- comment with 'a --' comment -- test comment (add1) select 'text\'s' from foo --escaped ... (add2) select 'text\'s' from foo --escaped' ... (add3)