我正在尝试使用Python的re.sub()
来匹配字符串和e
字符,并在e
字符之后和lastdigit之后立即插入大括号。例如:使用大括号包装数字的正则表达式?
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
使用两个反向引用时出现问题。
>>> 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
任何人都可以指出我的问题吗?谢谢您的帮助。
好极了,感谢您的帮助。幕后花絮非常酷。 – drbunsen
在第二种解决方案中,为什么使用'r'{\ 1}'而不是'r'{\ 2}'替换?我尝试使用'r'{\ 2}',但是这导致了一个错误。在后面的引用中是否支持后面的内容? – drbunsen
@ dr.bunsen正确,后视是一个非捕获组。 – agf