How to use variables in Python regular expression?

The following code demonstrates the use of variables in Python regex.

The variable cannot contain any special or meta characters or regular expression. We just use string concatenation to create a string.


import re
s = 'I love books'
var_name = 'love'
result ='(.+)'+var_name+'(.+)',s)
print result
var_name = 'hate'
s2 = 'I hate books'
result ='(.+)'+var_name+'(.+)',s2)
print result


This gives the output

<_sre.SRE_Match object at 0x000000000472FF10>
<_sre.SRE_Match object at 0x0000000004881030>

Updated on: 02-Nov-2023

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started