Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - using variable in regex

Tags:

python

regex

When I run the below piece of code, Im not getting the expected output. 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'm getting the below one,

root@test06> python test.py
test06
/etc/hosts1
test06
/etc/sysconfig/network1
root@test06>
like image 391
Gopi Avatar asked Sep 16 '26 07:09

Gopi


2 Answers

replace this:

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

to :

if re.search(NodeName,infile):

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

here is the 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
like image 75
Hackaholic Avatar answered Sep 17 '26 22:09

Hackaholic


Drop the quotes if NodeName is string it should just do string search in 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 goodies you can concat the variable to create regular expression string and pass it to re.search.

Also, if you don't need any regular expression stuff, just plain old substring search, you can use string function find used as follows:

if file.find(NodeName):
    print "DOOO"
like image 33
Nebril Avatar answered Sep 17 '26 21:09

Nebril



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!