Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex:combining re pattern format with a variable

Tags:

python

regex

I would like to combine a python variable and pattern. How can I do it?

below is what I would like to do.

re.search(r'**some_variable+pattern**',str_for_pattern_match,flags)

Thanks for your help.

like image 599
pranay reddy Avatar asked Dec 29 '11 11:12

pranay reddy


2 Answers

Regular expression patterns are not some special extra thing that Python treats specially. A pattern is just a perfectly ordinary string value, which the re module will interpret as a pattern.

So the question isn't "how can I use a variable in a pattern?", but rather "how can I construct a string based on a variable?".

The Python docs have plenty of information on how to do this. Particularly useful will be the documentation on string methods. The most important of these for the purpose of constructing regular expressions is probably will probably be str.format (as demonstrated in eumiro's answer), which has a large section of its own describing how to format basic data types into template strings in almost any way you could desire.

If you can master the basic operations on strings, then sticking a variable into a regular expression will be the least of what you can do!

like image 124
Ben Avatar answered Oct 20 '22 05:10

Ben


An update for using Python's f-string syntax (possibly the easiest of them all):

re.search(rf'**{some_variable}pattern**',str_for_pattern_match,flags)
like image 44
Paul Avatar answered Oct 20 '22 05:10

Paul