Regular Expressions (regex) make it easy to match wide range of strings in any programming language, be it back end languages like Python or front end languages like JavaScript. Often we use constant numbers and alphabets to define our regular expressions. But sometimes you may need to use a variable in regular expressions to make them more dynamic. In this article, we will learn how to use variable in Regex in Python.
How to Use Variable in Regex in Python
Here are the steps to use variable in Regex in Python. This is useful if you want to define your regular expression on the fly using user input variables. Let us say you want to build the following regular expression with a variable TEST in it, where \d is a regex for digits. We want a regex where the value of variable TEST has digits before and after it.
TEST='abc' r"\dTEST\d"
If you use the above expression, it will not give the desired result. Instead you need to build the regex as a string, as shown below.
TEST = 'abc my_regex = r"\d" + re.escape(TEST) + r"\d"
In the above code, we have used re.escape() to escape any special characters present in your regex string. You can directly concatenate the variable if you want as shown below.
TEST = 'abc' my_regex = r"\d" + TEST + r"\d"
Here is an example to where we accept variable’s value as user input, use it to create regex and use the regex in search() function.
TEST = sys.argv[1] my_regex = r"\d" + re.escape(TEST) + r"\d" if re.search(my_regex, subject, re.IGNORECASE): #do something
Alternatively, you can also use literal string interpolation (also called f-strings), from python 3.6. Here is an example of creating above regex.
TEST = sys.argv[1] my_regex = r"\d" + {TEST} + r"\d" if re.search(my_regex, subject, re.IGNORECASE): #do something
If you want to escape special characters in your variable used in regex, then use re.scape() function for the same.
TEST = sys.argv[1] my_regex = r"\d" + {re.escape(TEST)} + r"\d" if re.search(my_regex, subject, re.IGNORECASE): #do something
In this article, we have learnt how to use variable in regex. It is useful if you want to dynamically create regular expressions based on variable values, or based on user input.
Also read:
How to Split Array into Chunks in JavaScript
How to Print Number With Commas As Thousands Separator
How to Mount Remote Filesystem in Linux
How to Copy Files form Linux to Windows
How to Set Process Priority in Linux
Related posts:
How to Flatten List of Lists in Python
How to Find Index of Item in List in Python
How to Read File Line by Line Into Python List
How to List All Virtual Environments in Python
How to Convert List to String in Python
How to Concatenate Items in List Into String in Python
How to Create Python Dictionary from String
How to Merge PDF Files Using Python
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.