Something confusing about non-greedy reg exp match

7stud bbxx789_05ss at yahoo.com
Mon Sep 7 02:59:13 EDT 2009


On Sep 6, 8:46 pm, "gburde... at gmail.com" <gburde... at gmail.com> wrote:
> If I do this:
>
> import re
> a=re.search(r'hello.*?money',  'hello how are you hello funny money')
>
> I would expect a.group(0) to be "hello funny money", since .*? is a
> non-greedy match. But instead, I get the whole sentence, "hello how
> are you hello funny money".
>
> Is this expected behavior?

Yes.  search() finds the *first* match.  The non-greedy quantifier
does not transform search() into a function that finds all possible
matches and then picks the shortest one.  Instead, the non-greedy
quantifier causes search() to return the shortest possible first match
(v. the default which is the "longest possible first match").  In your
case, there is only one possible first match, so the non-greedy
quantifier does nothing.




More information about the Python-list mailing list