How to use a variable inside a regular expression with Python?

Sometimes, we want to use a variable inside a regular expression with Python.

In this article, we’ll look at how to use a variable inside a regular expression with Python.

How to use a variable inside a regular expression with Python?

To use a variable inside a regular expression with Python, we can create regex string with rf.

For instance, we write

if re.search(rf"b(?=w){re.escape(TEXTO)}d{{2}}b(?!w)", subject, re.IGNORECASE):
    print("match")

to call re.search with the rf"b(?=w){re.escape(TEXTO)}d{{2}}b(?!w)" regex string.

We interpolate the string returned by re.escape(TEXTO) in the string.

And we use the string to look for pattersn with the TEXTO value and 2 digits.

Conclusion

To use a variable inside a regular expression with Python, we can create regex string with rf.