I have tried the following expression, $_=~s/^#.*$//; $_ =~ s/([^"|'](#)+.*[^"|'])\s*#.*$/$1/; $_ =~ s/[^"|']#.*[^"|']$//;