Reputation: 1001
Can anyone explain why print match.group() only returns the resulting matches the first time it is called in a for loop below? I would expect it to print the matches every time it is called. I encountered this example while going through this section in Python Docs: Regex HOWTO
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> p = re.compile('\d+')
>>> iterator = p.finditer('12 drummers, 11 pipers, 10 dancers')
>>> iterator
<callable-iterator object at 0x107deabd0>
>>> for match in iterator:
... print match.group()
...
12
11
10
>>> for match in iterator:
... print match.group()
...
>>>
Upvotes: 2
Views: 5583
Reputation: 4359
This is the behavior described by the python documentation for iterator
.
Quoting the docs:
The intention of the protocol is that once an iterator’s next() method raises StopIteration, it will continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken.
You read all the items in the iterator in the first for ... in
loop, so there is nothing left to read.
If you want to go through the matches again, you'll need to get a new iterator:
>>> iterator = p.finditer('12 drummers, 11 pipers, 10 dancers')
Upvotes: 2
Reputation: 229371
p.finditer()
returns an iterator which yields the matches. Once the iterator is run all the way through once, the iterator is exhausted. It's the same as if you do this:
>>> l = [1, 2, 3]
>>> it = iter(l)
>>> for val in it:
print val
1
2
3
>>> for val in it:
print val
>>>
That is, you're never calling match.group()
in the second for loop. If you were, and it didn't return anything, you should instead have expected to see some None
s printed out.
Upvotes: 2