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.
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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With