我正在撰寫一個 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);
替換函式名是微不足道的,但是用格式說明(%i,%d等),只有當出現在日志運算式是沒有的。在%i中:
printf("this is an integer: %i", 1);應該是不變。我嘗試使用環視來隔離old_log_info(和最近的子串);:
re.sub(r'(?s)(?<=old_log_info)(?=\);)', '{}', code)
但我不知道如何只替換該匹配項中的格式說明符而不是整個匹配項。
uj5u.com熱心網友回復:
您可以使用兩層正則運算式。一種用于查找進行更改的函式,另一種用于實際進行更改。
下面是一個邏輯的例子。請注意,如果函式中的文本包含);,則不起作用,在這種情況下,最好通過決議替換正則運算式的第一級(如果是這種情況,請提供代碼示例)。
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)
輸出:
some code %i
new_log_info("this is an integer: {}, this is a double: {}", 1, 2.0);
printf("this is an integer: %i", 1);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/391011.html
下一篇:只找到多行C注釋而不是單行C注釋
