That's kind of an odd requirement. Is this homework? It makes more sense to just extract the first five words and then append whatever you want. The way you posed it awkward and should be reframed.

Hmmm... on further thought the expanded code with the conditional really just looks like a plain replacement. I've added a second code block where I turn this into a substitution.

The original code. This will clobber $text if there are less than five words.

# Capture the first five words including whitespace. ($text) = $text =~ / (\S+ \s+ \S+ \s+ \S+ \s+ \S+ \s+ \S+ )/x; # Shrink any internal whitespace $text =~ s/\s+/ /g;

The amended code to compensate for the previous block's clobbering action

# Capture the first five words including whitespace. if ( $text =~ / (\S+ \s+ \S+ \s+ \S+ \s+ \S+ \s+ \S+ )/x ) { # The regex extracted the first five words $text = "$1 ..."; # Shrink any internal whitespace $text =~ s/\s+/ /g; }

That previous block really looked like a substition. Here it is, reframed again

if ( $text =~ s/ (\S+ \s+ \S+ \s+ \S+ \s+ \S+ \s+ \S+ )/$1 .../x ) { # The match succeeded, shrink the white space $text =~ s/\s+/ /g; }

Updated Altered $text .= "whatever" to $text .= " ...". Also added caveats on word count


Seeking Green geeks in Minnesota


In reply to Re: get first e.g. 5 words and replace the remaining string with ... with one regex by diotalevi
in thread get first e.g. 5 words and replace the remaining string with ... with one regex by dreamy

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.