简体   繁体   中英

Back-referencing in Python

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 ([az]+)\\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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM