use warnings; use strict; my @c = ("a { b } c ( d ) e", "a { b } c ( d ) e {{F}} ((G))"); print replace($_), "\n" for @c; sub replace { my $d = shift; my $nobrackets = qr/([^{}]+)/; $d =~ s/\{$nobrackets\}/leftbracket $1 rightbracket/g; return $d; }