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

Python Regex re.sub not working as intended with dictionary lookup function?

I have one Py file working as a lookup like (constants.py):

constants = {'[%IP%]':'0.0.0.0'}

From my main file, I’m trying to replace a part of my string using the lookup.

from constants import constants
import re
path = r"[%IP%]\file.exe"
pattern = r'\[%.*?\%]'
def replace(match):
    return constants.get(match)
print(replace("[%IP%]")) # this bit works fine
print(re.sub(pattern, replace, path)) # this results in the matched pattern just vanishing

When I directly access the ‘replace’ function in my main file, it correctly outputs the matched result from the constants file dictionary.
But when I use the re.sub to substitute the pattern directly using the replace function with the lookup, it results in a string without the matched pattern at all.

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

So this is essentially the output for this (which isn’t correct):

0.0.0.0
\file.exe

The desired output for this is:

0.0.0.0
0.0.0.0\file.exe

Please help me fix this.

>Solution :

The callback you pass to re.sub will be called with a Match object, not with a plain string. So the callback function needs to extract the string from that Match object.

Can be done like this:

def replace(match):
    return constants.get(match[0])
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