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…
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;