my $res = { re1 => { foo => 'foo_new' }, re2 => { bar => 'bar_new' }, re3 => { qux => 'bar_new' }, re4 => { foobar => 'foobar_new' } }; my @required = qw ( re1 re2 re4 ); my %active_re = map{ each %{$res->{$_}} } @required; my $match = join '|', sort{ length $b <=> length $a } keys %active_re; $match = qr/($match)/; $str = 'foo bar baz foobar'; $str =~ s/$match/$active_re{$1}/g; print $str;