これは簡単な例です。
import re
math='<m>3+5</m>'
print re.sub(r'<(.)>(\d+?)\+(\d+?)</\1>', int(r'\2') + int(r'\3'), math)
それは私にこのエラーを与えます:
ValueError: invalid literal for int() with base 10: '\\2'
and\\2
の代わりに送信します。3
5
なんで?どうすれば解決できますか?
関数を使用する場合は、式ではなく関数re.sub
を渡す必要があります。ここに記載されているように、関数は引数としてmatchオブジェクトを取り、置換文字列を返す必要があります。通常の方法などでグループにアクセスできます。例:.group(n)
re.sub("(a+)(b+)", lambda match: "{0} as and {1} bs ".format(
len(match.group(1)), len(match.group(2))
), "aaabbaabbbaaaabb")
# Output is '3 as and 2 bs 2 as and 3 bs 4 as and 2 bs '
関数は文字列を返す必要があることに注意してください(元の文字列に戻されるため)。
ラムダ関数を使用する必要があります。
print re.sub(r'<(.)>(\d+?)\+(\d+?)</\1>', lambda m: str(int(m.group(2)) + int(m.group(3))), math)