

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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>
- Related Questions & Answers
- How to use wildcard in Python regular expression?
- How to use range in Python regular expression?
- How to use special characters in Python Regular Expression?
- Regular Expression Special Variables in Perl
- How to write a Python regular expression to use re.findall()?
- How do we use Python Regular Expression named groups?
- How do we use re.finditer() method in Python regular expression?
- How to use regular expression in Java to pattern match?
- How to use regular expression in class path in TestNG.xml?
- How do we use Python regular expression to match a date string?
- How to match parentheses in Python regular expression?
- How do we use a delimiter to split string in Python regular expression?
- How to use Python Regular expression to extract URL from an HTML link?
- Why do we use re.compile() method in Python regular expression?
- Regular Expression Examples in Python
Advertisements