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.

Example

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

Output

This gives the output

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

Updated on: 02-Nov-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements