线路.更换替换为值,即使是部分键匹配,而不是整个键匹配

2024-04-23 13:52:25 发布

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

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

问题:它正在取代应用程序.baseUrlbaseUrl=“http://'+ip+':9000而不是应用程序.baseUrl=“http://'+ip+':9000,因为baseUrl在应用程序.baseUrl. 你知道吗

只有当键匹配整个字符串而不是字符串的一部分时,如何替换它

文件名:abc.config文件你知道吗

你知道吗应用程序.baseUrl="http://ip:9000英寸

基本URL=“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

  }

}

}


Tags: keyinimportip应用程序httpsizeapplication
2条回答

您可以改用正则表达式:

re.sub(r"\b((?:application\.)?baseUrl)\b", r"\1=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"""
  \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.

因为您希望精确匹配而不是检查:

if key in line:

你应该做:

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

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

if line.startswith(key):

相关问题 更多 >