Monday, June 11, 2012

Python re.match doesn't guarantee $

When choosing a method to call with Python's re module, it's common to consider search() vs match(). However, note that:

re.match('pattern', s)
is not the same as'^pattern$', s)

re.match only guarantees that the beginning of the string is matched, not that the entire string is a match. Some simple examples:

>>> re.match('[a-z]+', 'abc123')
<_sre.SRE_Match object at 0x7f92136abc60>
>>> re.match('[a-z]+$', 'abc123')

Note that the second match statement guarantees that the match extends to the end of the string.

No comments:

Post a Comment