如何将特定regex应用于特定lin

2024-09-29 19:29:05 发布

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

我正在尝试在特定行上应用特定的正则表达式,该行由起始键指定: 现在,我将文件的内容放在python变量my\u config中


file content
---------------------------------------------
[paths]
path_jamjs: C:/Users/[changeUsername]/AppData/Roaming/npm/node_modules/jamjs/bin/jam.js
path_php: C:/[changeUsername]/php/php.exe

values to replace
---------------------------------------------
"path_jamjs": { "changeUsername": "Te" },
"path_php": { "changeUsername": "TeS" },

with open ("my.ini", "r") as myfile:
  my_config = myfile.read()

如何对我的配置中的整个文件内容应用regex replace来替换特定对应行上的值,而不必逐行循环,我可以用regex来完成吗?

给予

path: path_php
key: changeUsername
value: Te

改变

path_jamjs: C:/Users/[changeUsername]/AppData/Roaming/npm/node_modules/jamjs/bin/jam.js
path_php: C:/[changeUsername]/php/php.exe

path_jamjs: C:/Users/[changeUsername]/AppData/Roaming/npm/node_modules/jamjs/bin/jam.js
path_php: C:/Te/php/php.exe

Tags: pathmodulesnodenpmbinmyjsexe
1条回答
网友
1楼 · 发布于 2024-09-29 19:29:05
with open ("my.ini", "r") as myfile:
    my_config = myfile.read()

lines = my_config.splitlines(True)
replacements = {"path_jamjs": {"changeUsername": "Te"},
                "path_php": {"changeUsername": "TeS"}}

for path, reps in replacements.items():
    for i, line in enumerate(lines):
        if line.startswith(path + ':'):
            for key, value in reps.items():
                line = line.replace('[' + key + ']', value)
            lines[i] = line

result = ''.join(lines)

相关问题 更多 >

    热门问题