- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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>
Advertisements
To Continue Learning Please Login
Login with Google