my $string = qq~'tom's is silly','some','peter said it's okay'~; $string =~ s/(?!,)'s/\\'s/g; print "$string\n"; #output: 'tom\'s silly',\'some','peter said it\'s okay' #desired output: 'tom\'s is silly','some','peter said it\'s okay' # In the desired output, the single quote before "some" is not escaped