re.match versus re.findall

J

JerryB

Hi,
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?

Thanks!
Jerry
 
P

Peter Hansen

JerryB said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top