Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a variable into my re.compile expression

So I am trying to look through a file for a keyword that is represented by the variable what2look4. Whenever I run this program however it keeps returning blank data. The code is as follows:

regex2=re.compile(".*(what2look4).*")

I believe the problem is that the file is being searched for what2look4 as a string in itself instead of what that variable represents. Please correct me if I'm wrong, thanks for the help.

like image 921
Kprakash Avatar asked Jul 08 '14 17:07

Kprakash


People also ask

Can you put a variable in regex Python?

Can you put a variable in regex Python? Use string formatting to use a string variable within a regular expression. Use the syntax "%s" % var within a regular expression to place the value of var in the location of the string "%s" .

What is re compile () in Python?

Python's re. compile() method is used to compile a regular expression pattern provided as a string into a regex pattern object ( re. Pattern ). Later we can use this pattern object to search for a match inside different target strings using regex methods such as a re.


2 Answers

You can do it like so...

>>> regex2 = re.compile('.*(%s).*'%what2look4)

Or you can use format:

>>> regex2 = re.compile('.*({}).*'.format(what2look4))
like image 103
hwnd Avatar answered Sep 19 '22 14:09

hwnd


Use a String format:

search = "whattolookfor"
regex2=re.compile(".*({}).*".format(search))

The {} inside the string will be replaced with whattolookfor

like image 29
14 revs, 12 users 16% Avatar answered Sep 19 '22 14:09

14 revs, 12 users 16%