How to use variables in Python regular expression?

PythonServer Side ProgrammingProgramming

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>
raja
Published on 10-Jan-2018 15:27:57
Advertisements