line.replace 正在替换键匹配的一部分而不是整个键匹配的值

line.replace is replacing with value even for a portion of key match instead of entire key match

#!/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()

问题:它将 application.baseUrl 替换为 baseUrl="http://'+ip+':9000 instead of application.baseUrl="http://'+ip+':9000 因为 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

  }

}

}

您可以改用正则表达式:

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

这将匹配 application.baseUrl,替换为 application.baseUrl=http://IP_ADDRESS_HERE:9000,以及 baseUrl,替换为 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"""
                               # 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"=http://" + ip + ":9000"` precisely.

因为您想要精确匹配而不是检查:

if key in line:

你应该做的:

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

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

if line.startswith(key):