Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I use named backreference with re.sub?

I need to replace only full words so need to use backreference.
Re.sub works when using backreference:

import re

text = """
a=chef;
b=achefile;
"""

print(re.sub(r'([^\w])chef([^\w])', r'\1boss\2', text))

results (expectedly) in:

a=boss;
b=achefile;

However, what to do if I want to replace with a ‘0’?
The same regex breaks because the \1 is interpreted as \10…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print(re.sub(r'([^\w])chef([^\w])', r'\10\2', text))

I could not find how to use named groups with re.sub.
The search string would be:

r'(?P<start>[^\w])chef([^\w])'

but what will the replace string be?

>Solution :

Use \g<id>:

print(re.sub(r'([^\w])chef([^\w])', r'\g<1>0\g<2>', text))

# Output
a=0;
b=achefile;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading