my $rstr = reverse $string; $rstr =~ s/X(?!Y|\Z)//g; # note \Z, not $ $string = reverse $rstr;