0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! it works. Could you plz paste the document URL relevant to this topic, so I could get an overall comprehension of it.
@Judking: The Python regex howto (in the core docs) is probably your best start: docs.python.org/2/howto/regex.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.