It's your .+ at the beginning: it will always match the largest possible thing it can. In this case, it can match all the way up to the Protocol section, so it does. Change it to .+? and you'll be on the right track. The additional question mark tells the .+ to match the smallest possible thing it can. However, now the capturing (.+) will try to grab the largest possible match, so it will end up with "admin ] Protocol [ Telnet".

I think the negated character class [^\]]+ would be a better choice (grab as many non-brackets as possible) to match everything inside the brackets without risk of flowing over into the next set of brackets.     s/.+?\[\s+([^\]]+)\s+\].+/$1/; This works for me and results in 'admin'.

Also, as Mr. Muskrat demonstrates, this is not quite the right realm for a s///, you should probably be just using a match and capturing what you want.

blokhead


In reply to Re: My regex is too greedy! by blokhead
in thread My regex is too greedy! by hans_moleman

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.