Negative Lookahead Problem

Roger Day roger.day at globalgraphics.com
Fri Dec 6 10:02:30 EST 2002


"Terry Reedy" <tjreedy at udel.edu> writes:
>  n Thu, Dec 05, 2002 at 12:11:54PM +0000, Roger Day wrote:
> 
> > import re
> >
> > path = ["/users/dibbl","users/rsrc"]
> > print "expect 1st element to be selected"
> > m = re.compile(".*(?!rsrc$)")
> > for p in path:
> >     kk = m.match( p )
> >     if kk:
> >         print p
> 
> > > expect 1st element to be selected
> > > /users/dibbl
> > > users/rsrc
> 
> > > In the first test case, the negative-lookahead "fails"
> 
> I suspect its because .* matches (gobbles up) the whole string,
> which is then not followed by whatever.  I think the suggestion
> to use .endswith() is a good one.
> 
> TJR

I solved it with re.compile("(?!.*rsrc$)") which is good enough for
 what I want. I hadn't thought of endswith but, in this case, 
I'm passing a match to a recusive function - I was hoping that the 
regexp would be general enough to avoid adding extra non-regexp 
syntax to the place where it did the matching. So, no "not", 
as that would restrict the sort of regexp I could use.

I'd suspected the gobbling but I just wasn't *sure*.

Thanks for the replies everyone.

Roger.



More information about the Python-list mailing list