Python を使用しre.sub()
て文字列を文字と一致させ、文字のe
直後と最後の桁の後に中かっこを挿入しようとしてe
います。例えば:
12.34e56 to 12.34e{56}
1e10 to 1e{10}
目的の中括弧を挿入するための正しい正規表現が見つからないようです。たとえば、次のように左中かっこを適切に挿入できます。
>>> import re
>>> x = '12.34e10'
>>> pattern = re.compile(r'(e)')
>>> sub = z = re.sub(pattern, "\1e{", x)
>>> print(sub)
12.34e{10 # this is the correct placement for the left brace
2 つの後方参照を使用すると、問題が発生します。
>>> import re
>>> x = '12.34e10'
>>> pattern = re.compile(r'(e).+($)')
>>> sub = z = re.sub(pattern, "\1e{\2}", x)
>>> print(sub)
12.34e{} # this is not what I want, digits 10 have been removed
誰でも私の問題を指摘できますか? 助けてくれてありがとう。