Python - using variable in regex

When I run the code below, I don't get the expected result. Please correct me.

import socket
import re
NodeName=socket.gethostname()
change_hostname_list=['/etc/hosts1','/etc/sysconfig/network1']
for file in change_hostname_list:
        infile=open(file,'r').read()
        print NodeName
        print file
        if re.search('NodeName',file):
                print "DOOO"

      

I need the output "DOOO"

I am getting below one,

root@test06> python test.py
test06
/etc/hosts1
test06
/etc/sysconfig/network1
root@test06>

      

+3


source to share


3 answers


replace this:

if re.search('NodeName',file):

      

to:

if re.search(NodeName,infile):

      



you don't need a quote for the variable, the file variable is the filename from the list, the variable file has the file content.

here is a demo:

>>> import socket
>>> import re
>>> f = open('/etc/hosts')
>>> host_name =  socket.gethostname()
>>> host_name
'hackaholic'
>>> for x in f:
...     print(x)
...     if re.search(host_name,x):
...         print("found")
... 
127.0.0.1   localhost

127.0.0.1   hackaholic

found     # it founds the host name in file
# The following lines are desirable for IPv6 capable hosts

::1     localhost ip6-localhost ip6-loopback

ff02::1 ip6-allnodes

ff02::2 ip6-allrouters

      

+1


source


Strip the quotes if NodeName is a string, it should just do a string search in the file.

import socket
import re
NodeName=socket.gethostname()
change_hostname_list=['/etc/hosts1','/etc/sysconfig/network1']
for file in change_hostname_list:
    infile=open(file,'r').read()
    print NodeName
    print file
    if re.search(NodeName,file):
        print "DOOO"

      

If you need to use some regex, you can include this variable to create regex string and pass it to re.search

.



Also, if you don't want any of the regexp elements, just an old substring search, you can use the string function find

used like this:

if file.find(NodeName):
    print "DOOO"

      

+1


source


You seem to be passing a string 'NodeName'

to re.search()

as a template instead of a variable NodeName

. Remove the single quotes on line 9 of the code you provided.

0


source







All Articles