Why no match?

Alex Martelli aleax at aleax.it
Mon Dec 17 22:11:32 CET 2001


Robin Becker wrote:

> I'm puzzled as to why the second of these pattern matches fails. They
> only differ in that the second is supposed to match to the end of line.
> Can any regexpert supply an answer?

While waiting for regexperts, here's my take on it:

>>>> import re
>>>> re.compile(r'^self\s*\.\s*test\s*=\s*\d\s*').match('self.test=11')
> <SRE_Match object at 010711F8>

Sure, this matches -- look at the end of the pattern: an equal sign, 0 or 
more spaces, one digit, zero or more spaces, no constraints on what comes 
after.  This part I just described in words matches the '=1' part of the 
argument to method match, no?

>>>> re.compile(r'^self\s*\.\s*test\s*=\s*\d\s*$').match('self.test=11')
>>>> 

But this specifies that the string ends after the match, and it doesn't, as 
it has an extra digit '1' at the end.  So, the result is None.

Maybe you want \d+ (one *or more* digits) in the pattern rather than just 
\d (*exactly* one digit) as you have now?


Alex





More information about the Python-list mailing list