perl -e' $string = "X*X*X*X"; $NEW = 20; $string =~ s/ (?: ^ | \* ) \K X (?= \* | $ ) /$NEW/xg; print "$string\n"; ' 20*20*20*20