How to use a variable inside a regular expression?

Pedro Lobito picture Pedro Lobito · Aug 3, 2011 · Viewed 221.8k times · Source

I'd like to use a variable inside a regex, how can I do this in Python?

TEXTO = sys.argv[1]

if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

Answer

Ned Batchelder picture Ned Batchelder · Aug 3, 2011

You have to build the regex as a string:

TEXTO = sys.argv[1]
my_regex = r"\b(?=\w)" + re.escape(TEXTO) + r"\b(?!\w)"

if re.search(my_regex, subject, re.IGNORECASE):
    etc.

Note the use of re.escape so that if your text has special characters, they won't be interpreted as such.