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)


In reply to Re: greedy match of words by moritz
in thread greedy match of words by newbio

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.