[Baypiggies] Bug in re module?

Dirk Bergstrom dirk at otisbean.com
Thu Nov 29 20:10:58 CET 2012


On 11/29/2012 10:57 AM, Mitch Patenaude wrote:
> Maybe I'm misunderstanding, but I think I have a bug in the re module:
> mpatenaude-mbp:tmp mpatenaude$ python2.7
> Python 2.7.3 (default, Apr 13 2012, 00:05:08)
> [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> import re
>  >>> line="\tTest2.1\n"
>  >>> matchobj = re.match('Test2.1',line,0)
>  >>> matchobj
> It's not matching a very simple string.
> It *works* if I use findall rather than match, but I don't understand why.

The docstring for re.match says:

   Try to apply the pattern at the start of the string, returning
   a match object, or None if no match was found.

You're asking if 'Test2.1' is found at the beginning of line, which it 
isn't.  The method you want is re.search:

   Scan through string looking for a match to the pattern, returning
   a match object, or None if no match was found.

In [6]: line="\tTest2.1\n"

In [7]: re.search('Test2.1',line,0)
Out[7]: <_sre.SRE_Match at 0x2417b28>

If I was Emperor of the Universe the re.match method would have been 
deprecated ages ago.

-- 
Dirk Bergstrom
dirk at otisbean.com
http://otisbean.com/


More information about the Baypiggies mailing list