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.'
Last modified: 2016-10-03 | ||
|
||
|
||
© Shin Nakamura/BasicWerk 2008 - 2024 |