I have a large txt file, which I want to edit using Python's re
module.
Once I find the strings that match my regular expression, I want to make some changes to them and write them back to the txt file.
For example,
Original text
9 multiplied by 2 is
ans =
18
Desired output:
9 multiplied by 2 is 18.
In Atom, I can do this by searching for ([a-z]+)\s+ans\s=\s+(\d+)
and replacing with $1 $2
.
The $
grouping does not work with .sub()
in Python. Any tips on how I can implement this type of backreferencing?
EDIT: I am using ?P<tag>
for backreferencing, but that breaks down if I try to do multiple substitutions using a dictionary.