[tpm] Greedy regex question

Jim Graham james.a.graham at gmail.com
Fri Feb 29 08:24:50 PST 2008


   It's not really greedy, per-se. It's what you are asking for. Find  
the first "(" followed by any character(s), followed by a ")" at the  
end of the string. Greedy/non-greedy means, basically, given a  
starting point, go as far as you can (greedy) or go as short as you  
can (non-greedy). By forcing the last ")" to be at the end of the  
string, they become the same thing. Note non-greedy doesn't mean find  
the shortest possible match (which is what you want).

   I will try to come up with a solution you want.

   - jim

On 29-Feb-08, at 11:07 AM, Madison Kelly wrote:

> Hi all,
>   Given the string:
> $val="0  (0x0)  (int)";
>   Why does:
> $val=~s/\(.*?\)//;
>   Properly, ungreedily, return "0    (int)" *but*, changing it to:
> $val=~s/\(.*?\)$//;
>   Wrongly, greedily, return "0  "? When I put the '.*?' in brackets  
> and
> print '$1' on the later it is indeed grabbing "0x0)  (int".
>   What is it about anchoring the regex to the end of the string cause
> it to be a greedy regex again? As you can probably gather, I am trying
> to get rid of /only/ the last '(foo)' in a given string.
> Thanks!
> Madi
> _______________________________________________
> toronto-pm mailing list
> toronto-pm at pm.org
> http://mail.pm.org/mailman/listinfo/toronto-pm

More information about the toronto-pm mailing list