Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use a variable instead of a string inside regex search function in python

Tags:

python

regex

I have this regex function to extract a specific word in a string

fileName = re.search(r'path1\w([A-Za-z\d]+)', self.fileList[0]).group(1)

path1 is an actual string

What if I would like to replace it by fileName variable where fileName = "path1"

I tried:

print re.search(r'\w([A-Za-z\d]+)' % fileName, self.fileList[0]).group(1)

I got this error:

TypeError: not all arguments converted during string formatting

Why did I get this error ? how to solve this problem

like image 537
Mohamad Zein Avatar asked Dec 07 '25 06:12

Mohamad Zein


1 Answers

You need a %s in your regex :

print re.search(r'%s\w([A-Za-z\d]+)' % fileName, self.fileList[0]).group(1)

Or as a more pythoinc and flexible way you can use str.format function :

print re.search(r'{}\w([A-Za-z\d]+)'.format(fileName), self.fileList[0]).group(1)

Note that is second way if you have a list of file names you can loop over them and pass the file names to format.

like image 52
Mazdak Avatar answered Dec 08 '25 18:12

Mazdak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!