Memoize2

Python regexp finditer

正規表現がマッチする毎に何かしたい場合は finditer が使える。


$ python3
>>> import re

# テキストを用意
>>> text = """I 00 clear OK,
... ok
... swap pop Clear
... 09
... 
... 21."""

# 例えば数字にマッチする正規表現をコンパイル
>>> matchObj = re.compile(r'\d+')

# re.finditer はジェネレータである
>>> for m in matchObj.finditer(text) :
...     print(m.group(0))
... 
00
09
21

# ちなみに text を破壊的に更新しても、
# ジェネレータを生成した時点の text の内容を保持してくれている
>>> for m in matchObj.finditer(text) :
...     print(m.group(0))
...     text = text.replace(m.group(0), 'N')
# だから数字部分をもれなく print() した上で
00
09
21
# text 変数の内容は更新されている
>>> text
'I N clear OK,\nok\nswap pop Clear\nN\n\nN.'

参考: Python3 re — 正規表現操作

 

Last modified: 2016-10-03

Page Top

Index

Bw

Author: 中村 心 Shin Nakamura, Email: sn(at)i.basicwerk.com


© Shin Nakamura/BasicWerk 2008 - 2024