#!/usr/bin/perl use strict; use warnings; my $string = "A1 and A2 but not 1 and 2"; my $switch_hash = { 1 => 2, 2 => 1 }; my $regexp = '([A-Za-z])('.(join( '|', keys %$switch_hash )).')'; print "Regexp: $regexp\n"; my $comp_regexp = qr"$regexp"; $string =~ s/$comp_regexp/$1.$switch_hash->{$2}/ge; print $string, "\n";