即使对于一部分键匹配而不是整个键匹配,line.replace也会替换为值

时间:2015-01-23 23:48:25

标签: python regex python-2.7 python-3.x

#!/usr/bin/python
import socket
import subprocess

ip=socket.gethostbyname(socket.gethostname())

reps= {'application.baseUrl': 'application.baseUrl="http://'+ip+':9000"',
'baseUrl': 'baseUrl="http://'+ip+':9000"'
}

f = open('/opt/presentation/conf/application.conf','r+')
lines = f.readlines()

f.seek(0)
f.truncate()

for line in lines:
        for key in reps.keys():

            if key in line:
                line = line.replace(line, reps[key])
        f.write(line+'\n')
f.close()

问题:它正在用baseUrl =“http://'+ ip +':9000而不是application.baseUrl =”http://'+ ip +':9000替换application.baseUrl,因为baseUrl在application.baseUrl中。

如果只匹配整个字符串而不是字符串部分

,我该如何替换密钥

文件名:abc.config

application.baseUrl = “HTTP:// IP:9000”

的baseUrl = “HTTP:// IP:9000”

远程{

log-received-messages = on

netty.tcp {

  hostname = "ip"

  port = 9999

  send-buffer-size = 512000b

  receive-buffer-size = 512000b

  maximum-frame-size = 512000b

  server-socket-worker-pool {

    pool-size-factor = 4.0

    pool-size-max = 64

  }

  client-socket-worker-pool {

    pool-size-factor = 4.0

    pool-size-max = 64

  }

}

}

2 个答案:

答案 0 :(得分:0)

由于您需要完全匹配而不是检查:

if key in line:

你应该这样做:

if key == line[0:len(key)]:

或者更好,正如亚当在下面的评论中所建议的那样:

if line.startswith(key):

答案 1 :(得分:-1)

您可以使用正则表达式:

re.sub(r"\b((?:application\.)?baseUrl)\b", r"\1=http://{}:9000".format(ip))

这将匹配application.baseUrl,替换为application.baseUrl=http://IP_ADDRESS_HERE:9000baseUrl,替换为baseUrl=http://IP_ADDRESS_HERE:9000

正则表达式解释:

re.compile(r"""
  \b                             # a word boundary
  (                              # begin capturing group 1
    (?:                            # begin non-capturing group
      application\.                  # application and a literal dot
    )?                             # end non-capturing group and allow 1 or 0 occurrences
    baseUrl                        # literal baseUrl
  )                              # end capturing group 1
  \b                             # a word boundary""", re.X)

和替换

re.compile(r"""
  \1                             # the contents of capturing group 1
  =http://                       # literal
  {}                             # these are just brackets for the string formatter
  :9000                          # literal""".format(ip), re.X)
# resulting in `r"\1=http://" + ip + ":9000"` precisely.