Python Replace with regex

you may need to replace part of a string. When you are looking through the Python documentation and you would end up with  re.sub.

import re
s =
'<textarea id="Foo"></textarea>
output = re.
', 'Bar', s)print output

Unfortunately, this was not what you expected to print '<textarea id="Foo">Bar</textarea>', instead it will be 'bar'.

Instead of capturing the part you want to replace you can capture the parts you want to keep and then refer to them using a reference \1 to include them in the substituted string.
Try this instead:
output = re.sub(r'(<textarea.*>).*(</textarea>)', r'\1Bar\2', s)

I think you will be good.


Popular Posts