Use a variable in a regular expression

Sometimes you want to pass an object into a regular expression rather than explicitly state the pattern you're looking to match against.

An example of when you might want to do this is when you have a list of words and you want to iterate over a text and look for matches against the words in that list. 

Here's how this is done:

import re

subject = "In the room women come and go, talking of Michelangelo."

words = ['room', 'talking', 'Michelangelo']

for word in words:
    my_regex = r"\b(?=\w)" + re.escape(word) + r"\b(?!\w)"
    if, subject, re.IGNORECASE):
        print (word, ' found in the subject')