簡體   English   中英

如何將特定的正則表達式應用於特定的行

[英]how to apply a specific regex to a specific line

我試圖在由開始鍵指定的特定行上應用特定的正則表達式:現在我將文件內容包含在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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM