[英]replace all occurrences of a set of strings, which appear between two specific words
我正在編寫一個 python 腳本,它將幫助我使用 re.sub 功能替換 c++ 應用程序中的日志框架。
舊語法如下所示:
old_log_info("this is an integer: %i, this is a double: %d", 1, 2.0);
old_log_error("this is an integer: %i, this is a double: %d", 1, 2.0);
新語法:
new_log_inf("this is an integer: {}, this is a double: {}", 1, 2.0);
new_log_err("this is an integer: {}, this is a double: {}", 1, 2.0);
它也必須適用於多行語句,即:
old_log_info(
"this is an integer: %i, this is a double: %d",
1,
2.0);
應該變成:
new_log_inf(
"this is an integer: {}, this is a double: {}",
1,
2.0);
替換 function 名稱是微不足道的,但僅當不出現在日志記錄表達式中時才替換格式說明符( %i
、 %d
等)。 %i
in: printf("this is an integer: %i", 1);
應該保持不變。 我嘗試使用環視來隔離old_log_info(
和最近的);
,但我不知道如何只替換該匹配中的格式說明符而不是整個匹配。
您可以使用兩層正則表達式。 一種是找到進行更改的功能,另一種是實際進行更改。
下面是一個邏輯示例。 請注意,如果 function 中的文本包含);
,在這種情況下,最好通過解析替換第一級正則表達式(如果是這種情況,請提供代碼示例)。
code = '''some code %i
old_log_info("this is an integer: %i, this is a double: %d", 1, 2.0);
printf("this is an integer: %i", 1);'''
import re
def repl(m):
inside = re.sub('%[id]', '{}', m.group(2))
return f'new_log_info({inside});'
new_code = re.sub('(old_log_info)\((.*?)\);', repl, code)
Output:
some code %i
new_log_info("this is an integer: {}, this is a double: {}", 1, 2.0);
printf("this is an integer: %i", 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.