Python - 使用变量在正则表达式中

2024-09-30 12:21:11 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行下面的代码时,我没有得到预期的输出。 请纠正我。。你知道吗

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"

我需要输出“DOOO”

我得到下面的那个

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

Tags: importreetcsocketchangehostnamelistfile
3条回答

删除引号如果NodeName是字符串它应该只做字符串搜索文件。你知道吗

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"

如果您需要使用一些正则表达式,您可以连接变量来创建正则表达式字符串并将其传递给re.search。你知道吗

另外,如果您不需要任何正则表达式的东西,只需要简单的旧子字符串搜索,您可以使用字符串函数find,用法如下:

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

您似乎将字符串'NodeName'作为模式传递给re.search(),而不是变量NodeName。删除您提供的代码第9行中的单引号。你知道吗

替换此项:

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

收件人:

if re.search(NodeName,infile):

变量不需要引号,file variable是列表中的文件名,variable file包含文件的内容。你知道吗

演示如下:

>>> 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

相关问题 更多 >

    热门问题