First the regex that does what you want (as most regexes assuming a lot):
$line =~ s/\s+(\S+)\s+/:$1:/;
which will replace the first instance of
"a series of whitespace followed by a series non-whitespace followed by a series of whitespace",
with a
"colon, followed by the set of non-whitespace matched, followed by another colon".

You will have to modify this further to get the result you posted as it is also removing the set of spaces after "three" and replacing it with one space.

Any idea what I'm doing wrong?

Your code can be broken down to a pattern like so:
. will match any character besides \n. The {2} at the end means do this twice. This has to be followed by
\s+ which means the pattern has to have at least one whitespace character but will capture as many of these in a row as it can.
When your pattern matches the first time in the line it will replace it with a colon.

As per usual,let me direct you to perlre for your regex needs.

-enlil


In reply to Re: simple regex problem by Enlil
in thread simple regex problem by Anonymous Monk

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.