$ python -c 'import regex; print(regex.sub("^(?.)|(?.)$|(?.)", lambda m:m.lastgroup, "xxx"))' abc #### $ perl -E'say "xxx" =~ s/^(?.)|(?.)$|(?.)/@{[keys %+]}/gr' abc