0

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
protonpasta
  • 45
  • 1
  • 6

1 Answers1

0

in the re module instead of using $1 for group 1 you use \1 instead. This should allow you to keep your regex as is and convert any other regexes in a similar manner. The proper functionality and definitions are outlined in the re docs

Karan Shishoo
  • 2,402
  • 2
  • 17
  • 32
  • Thanks. This does not work if I try to do multiple substitutions [using a dictionary](https://stackoverflow.com/questions/15175142/how-can-i-do-multiple-substitutions-using-regex-in-python). Any idea how to solve that? – protonpasta Feb 11 '20 at 07:34
  • @aasthas if you are going to use a dictionary (which was not mentioned in your original question) you can look at [this](https://stackoverflow.com/q/22545114/6620283) question, which seems to doing the same thing that are attempting. – Karan Shishoo Feb 11 '20 at 07:40