Win8 Strawberry 5.30.3.1 (64) Sat 12/04/2021 21:26:27 C:\@Work\Perl\monks >perl -Mstrict -Mwarnings my $str='kklmn'; # +--------------- if you look ahead to kkl # | # | +---+-------- while also capturing it to capture group 1 # | | | (match point is not advanced) # | | | # | | | +-------- and then if capture 1 captured anything # | | | | # | | | | +----- match with what was captured to $1 # | | | | | # | | | | | +-- else match with mn # | | | | | | # | | | | | | +------- and substitute this # | | | | | | | # v v---v v v v v $str=~ s/(?=(kkl))(?(1)\g1|mn)/***/g; print "'$str' \n"; ^Z '***mn'