Python regex, pulling patterns out of a match and using them as input back into the match
Question: I have searched for an answer. I am sure they are out there, but there are way
too many false hits.

This is my script (my attempt fails):

    
    
    #!/bin/env python
    
    import re
    
    usage="""
        My favorite restaurant is <<<res>>>
        My favorite person is <<<per>>>
    """
    
    res="pizza hut"
    per="my sister"
    
    def main():
        value = re.sub(r'<<<(\w+)>>>', globals()[r'\1'], usage)
        print 'value=%s.' % (value)
    
    if ( __name__ == "__main__"):
        main()
    

What I am trying to output is:

    
    
    value=
        My favorite restaurant is pizza hut
        My favorite person is my sister
    .
    

The closest [answer](http://stackoverflow.com/questions/6206804/regex-to-
replace-variables) that I have seen, involves maintaining a separate list. I
do not want to have to maintain a separate list.


Answer: You can use a function as the replacement in `re.sub()`. The function will
receive the [match object](http://docs.python.org/2/library/re.html#match-
objects) 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.

