Skip to content Skip to sidebar Skip to footer

Python Regex Sub: Using Dictionary With Regex Expressions

I am using a dictionary that contain regular expressions to substitute portions of different strings, as elegantly described in a previous SO question by @roippi. The first 're.sub

Solution 1:

match.group(n) does not return the regular expression that was used to match the nth group, but the nth group itself.

The lambda therefore returns test_dict.get('999', '999'), which returns '999', because '999' is not a key in your dictionary.

You could iterate over the keys of the dictionary and check if any key matches your capture group, and then replace it, but that has O(n) time complexity (in the size of the dictionary).

defreplacement(match, d, group=1):
    for key in d:
        if re.match(key, match.group(group)):
            return d[key]
    return match.group(group)

re.sub(r'(\d+)', lambda x: replacement(x, test_dict), '999la')

Post a Comment for "Python Regex Sub: Using Dictionary With Regex Expressions"