how python interprets re matches
Steve Holden
steve at holdenweb.com
Thu Dec 15 15:36:12 EST 2005
Mike Rennie wrote:
> Hi, folks
>
> I'm still relatively new to the language, so I hope this question isn't too
> naive. It's a general question for anyone who might have some insights on
> Regular Expressions.
>
> According to Mark Pilgrim, author of "Dive Into Python", "If the regular
> expression matches, the method will return a Match object, which Python
> considers to be true" (Section 16.3, Example 16.8).
>
> So, I think "great", and write a function that returns a match object using
> re's.
>
> So i make some testcases. The test where there is no match, and the return from
> the function is None, passes.
>
> The test where there is a match, fails on the assertion:
>
> AssertionError: <_sre.SRE_Match object at 0x00AFB9C0> != True
>
> But, shouldn't it accept that as True, based on the info. in Dive Into Python?
> I suspect I am being naive in my interpretation of things, so if anyone has any
> feedback on how I might get this to work so my function just returns either
> True (if a match) or False (if no match), I welcome it.
>
You seem to be executing a snippet like
match = re.match(...)
assert match == True, "Some error message"
This isn't going to work. Basically, when Mark says "the interpreter
considers the match object to be true" all he really means is that the test
if match:
will succeed. This is in contradistinction to when the match fails, when
all re matching functions and methods return None, which tests false.
If you want to test that the match succeeds (and you aren't interested
in any other properties of the match object) the most straightforward
assertion would be
assert match is not None, "Something did not match"
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
More information about the Python-list
mailing list