perl -e ' $f = "\$foo \$(bar) \n"; $f =~ s/\$ (?: (\w+) | \((\w+)\) )/<$^N>/xg; print $f;' #### perl -e ' my $f = "\$foo \$(bar)"; our $val; # must use package global # for temporization in regex $f =~ s{\$ # the dollar (?: # outer altinator (\w+) (?{ $val = $^N }) # match and then store | \((\w+) (?{ $val = $^N }) \) # or match 2 and store ) # close outer }{<$val>}xg; print "$f\n"'