Judking
Judking

Reputation: 6371

how to replace via regex with group enclosed in python

Here's the scenario:

import re

if __name__ == '__main__':
    s = "s = \"456\";"
    ss = re.sub(r'(.*s\s+=\s+").*?(".*)', r"\1123\2", s)
    print ss

What I intend to do is to replace '456' with 123, but the result is 'J3";'. I try to print '\112', it turns out to be character 'J'. Thus, is there any method to specify that \1 is the group in regex, not something like a escape character in Python? Thanks in advance.

Upvotes: 0

Views: 57

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

Just change \1 to \g<1>

>>> re.sub(r'(.*s\s+=\s+").*?(".*)', r"\g<1>123\2", s)
's = "123";'

If there was no numbers present next to the backreference (like \1,\2), you may use \1 or \2 but if you want to put a number next to \1 like \11, it would give you a garbage value . In-order to differntiate between the backreferences and the numbers, you should use \g<num> as backrefernce where num refers the capturing group index number.

Upvotes: 1

Related Questions