in reply to My regex is too greedy!

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

Replies are listed 'Best First'.
Re: Re: My regex is too greedy!
by Nkuvu (Priest) on Mar 05, 2003 at 17:22 UTC

    Would this be a more efficient regex without the .+? at the beginning? You aren't, after all, capturing it...

      If we're doing just a m// match then you are certainly right. I was using s///, so I needed to match the whole string to replace it.

      blokhead

        Gah. Sorry, I missed that you were still looking at the s///. For some reason I was thinking you had switched it to a m//.