Pythonプログラミング言語における”re sub”ライブラリ、関数メソッドでの応用的な使用例として、関数を渡してコールバックし、処理を行う、というテクニックがあります。これにより、通常の正規表現、正規表現置換処理だけではできないような高度な置換処理が可能となります。
re.subではre.sub([正規表現], [置換], [テキスト])
のような文法ですが、この”置換”の部分をプログラマブルに変化させたい、それも”正規表現”でマッチした部分のグループマッチを使用して。
そういう場合、以下のように”置換”に関数やラムダを渡すことが出来ます。
(関数)
import re
number_mapping = {'1': 'one',
'2': 'two',
'3': 'three'}
def callback(x):
return number_mapping[x.group()]
print re.sub(r'\d', callback, "1 testing 2 3")
one testing two three
(ラムダ)
import re
number_mapping = {'1': 'one',
'2': 'two',
'3': 'three'}
print re.sub(r'\d', lambda x: number_mapping[x.group()], "1 testing 2 3")
one testing two three
regex – Passing a function to re.sub in Python – Stack Overflow
regex – Using a regular expression to replace upper case repeated letters in python with a single lowercase letter – Stack Overflow
関連記事:
Windows 11にPythonをインストールする
Pythonのバージョン管理をする方法とpyenvの使い方
Pycharmの有料版を無料でインストールするには
Pythonで投資の複利計算をする
Imagededupで類似画像を抽出、検出する(Python)
自然言語テキストが何語なのか判定する [fastText]
関連広告: