#!/usr/bin/perl while () { s/^ ~ .*? \K _ /+/x; print "$_"; } __DATA__ A line with an_underscore. A line with_two_underscores. ~A line with an_underscore starting with a tilde. ~A line with_two_underscores starting with a tilde.