#!/usr/bin/perl use strict; use warnings; while () { s/(<%(?:[^%]+|%[^>])*%>)|'/$1 || ""/eg; print; } __DATA__ Leave this line alone. Remove this quote ' and these two quotes '' from this line. Leave <% the first quote ' %> alone, but remove the second ' one. Remove from <% an open but not closed ' tag. ' Leading quote? <% Multiple ' tags %> ' on one ' <% line ''' work %> too ' ! #### Leave this line alone. Remove this quote and these two quotes from this line. Leave <% the first quote ' %> alone, but remove the second one. Remove from <% an open but not closed tag. Leading quote? <% Multiple ' tags %> on one <% line ''' work %> too !