re.match versus re.findall
Peter Hansen
peter at engcorp.com
Thu Feb 9 19:13:55 EST 2006
JerryB wrote:
> I have a string like this:
>
> invalidStr = "192.168.*.1"
>
> I want to be sure I don't get a * followed by a number, i.e. I want
> invalidStr to be invalid. So I do:
>
> numberAfterStar = re.compile(r'\*.*\d')
>
> Now, here's the fun:
>
> If I run:
> if numberAfterStar.findall(invalidStr):
> print "Found it with findall!"
>
> it prints, if I run:
>
> if numberAfterStar.match(invalidStr):
> print "Found it with match!"
>
> it doesn't.
> Why does findall finds a match it but match doesn't?
This might help:
>>> numberAfterStar.findall(invalidStr)
['*.1']
>>> numberAfterStar.match(invalidStr)
>>> numberAfterStar.search(invalidStr)
<_sre.SRE_Match object at 0x00AF3DB0>
Check the docs on match, specifically where it talks about when you
should use search() instead... (http://docs.python.org/lib/re-objects.html)
(By the way, thank you for the excellently crafted post. I wish
everyone who asked questions here took the time to prepare as thoroughly
and include the actual failing code, etc...)
-Peter
More information about the Python-list
mailing list