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)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值