[tpm] Greedy regex question

Dave Doyle dave.s.doyle at gmail.com
Fri Feb 29 08:35:53 PST 2008


I think that this really reflects one of the dangers of .* in regexes.

Would something like this:

    $var =~ s/\([^()]*)$//;

be closer?

by changing the .  to a negated character class disallowing brackets
it might be a bit closer.  This would always eliminate the bracketed
info at the end as well as not take edge cases with nested brackets.

-dave

On Fri, Feb 29, 2008 at 11:24 AM, Jim Graham <james.a.graham at gmail.com> wrote:
> Hi
>
>    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
>
>  _______________________________________________
>  toronto-pm mailing list
>  toronto-pm at pm.org
>  http://mail.pm.org/mailman/listinfo/toronto-pm
>



-- 
dave.s.doyle at gmail.com


More information about the toronto-pm mailing list