python3 RE finditer()不能使用next()属性

Mastering Python Regular Expressions 一书 用于python3.6时的订正

1) RE.finditer()不能使用next()方法

原文(第34页)

finditer(string[, pos[, endpos]])
Its working is essentially the same as findall, but it returns an iterator in which
each element is a MatchObject, so we can use the operations provided by this object.
So, it’s quite useful when you need information for every match, for example the
position in which the substring was matched. Several times, I’ve found myself using
it to understand what’s happening in findall.
Let’s go back to one of our initial examples. Match every two words and
capture them:

>>> pattern = re.compile(r"(\w+) (\w+)")
>>> it = pattern.finditer("Hello⇢world⇢hola⇢mundo")
>>> match = it.next()
>>> match.groups()
('Hello', 'world')
>>> match.span()
(0, 11)

In the preceding example, we can see how we get an iterator with all the matches.
For every element in the iterator, we get a MatchObject, so we can see the captured
groups in the pattern, two in this case. We will also get the position of the match.

>>> match = it.next()
>>> match.groups()
('hola', 'mundo')
>>> match.span()
(12, 22)

Now, we consume another element from the iterator and perform the same
operations as before. So, we get the next match, its groups, and the position
of the match. We’ve done the same as we did with the first match:

>>> match = it.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

Finally, we try to consume another match, but in this case a StopIteration exception
is thrown. This is normal behavior to indicate that there are no more elements.

订正(用于python3)

第1、2、3段代码合并然后修改如下:

pattern = re.compile(r"(\w+) (\w+)")
it = pattern.finditer("Hello world,hola mundo")
for match in it:
    print(match)
    print(match.groups())
    print(match.span())

运行结果:

<_sre.SRE_Match object; span=(0, 11), match='Hello world'>
('Hello', 'world')
(0, 11)
<_sre.SRE_Match object; span=(12, 22), match='hola mundo'>
('hola', 'mundo')
(12, 22)

猜你喜欢

转载自blog.csdn.net/zt5169/article/details/83660065