I am trying to using Python's re.sub()
to match a string with an e
character and insert curly braces immediately after the e
character and after the lastdigit. For example:
12.34e56 to 12.34e{56}
1e10 to 1e{10}
I can't seem to find the correct regex to insert the desired curly braces. For example, I can properly insert the left brace like this:
>>> 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
My problem arises when using two back references.
>>> import re
>>> x = '12.34e10'
>>> pattern = re.compile(r'(e).+($)')
>>> sub = z = re.sub(pattern, "\1e{\2}", x)
>>> prin开发者_如何学编程t(sub)
12.34e{} # this is not what I want, digits 10 have been removed
Can anyone point out my problem? Thanks for the help.
re.sub(r'e(\d+)', r'e{\1}', '12.34e56')
returns '12.34e{56}'
or, the same result but different logic (don't replace e
with e
):
re.sub(r'(?<=e)(\d+)', r'{\1}', '12.34e56')
Your brace placement is incorrect.
Here's a solution ensuring the that there's a number with optional decimal place before the e
:
import re
samples = ['12.34e56','1e10']
for s in samples:
print re.sub(r'(\d+(?:\.\d+)?)e([0-9]+)',"\g<1>e{\g<2>}",s)
Yields:
12.34e{56} 1e{10}
精彩评论