我正在尝试在由起始键指定的特定行上应用特定的正则表达式: 现在我的文件内容位于 python 变量 my_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()
如何对 my_config 中的整个文件内容应用正则表达式替换,以替换特定对应行的值,而不必逐行循环,我可以使用正则表达式执行此操作吗?强>
给定
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
最佳答案
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)
关于python - 如何将特定的正则表达式应用于特定的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16466209/