in reply to greedy match of words

You're nearly there. Two things that you need to improve: you don't need escape the star in the character class, it's just [^*]; and ($bagofwords)+ will only capture the last match of that regex.

Here's something that nearly works:

use warnings; use strict; use 5.010; my $line = '*Mary* had a little lamb'; my $bagofwords = qr{had |a |Sam |Tom}; if ($line =~ s/\*([^*]+)\*\s*((?:$bagofwords)*)/*$1 $2* /) { say $line; }

It outputs *Mary had a * little lamb. If you want to include the underscores, you might have to post-process $2 before interpolating it, possibly with the /e modifier.

In Perl 6 a quantified regex just returns a list of match objects, so that's a bit easier here:

use v6; token word { had | a | Sam | Tom } say '*Mary* had a little lamb'.subst: rx{ '*' (<-[*]>+) '*' \s+ [<word> \s+]+ }, { '*' ~ join('_', $0, @($<word>)) ~ '* ' };

Output: *Mary_had_a* little lamb

(Note that Rakudo doesn't yet implement s///, but the method form of substitutions work today)