w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Python regex, pulling patterns out of a match and using them as input back into the match

You can use a function as the replacement in re.sub(). The function will receive the match object as the only argument and should return a string. The best way to do this is to create a dictionary with your replacements:

import re

usage="""
    My favorite restaurant is <<<res>>>
    My favorite person is <<<per>>>
"""

rep = {"res": "pizza hut",
       "per": "my sister"}

print re.sub(r'<<<(w+)>>>', lambda m: rep.get(m.group(1),
""), usage)

You could use this exact same method with globals(), but using globals() in this way is generally discouraged when a dictionary offers the same behavior in a safer way.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.