在開發環境中,我想確保某些目錄中源檔案中的所有字串都包含在某個宏“STR_MACRO”中。為此,我將使用 Python 腳本決議源檔案,并且我想設計一個正則運算式來檢測帶有未包含在此宏中的字串的非注釋行。
例如,正則運算式應匹配以下字串:
std::cout << "Hello World!" << std::endl;
load_file("Hello World!");
但不是以下的:
std::cout << STR_MACRO("Hello World!") << std::endl;
load_file(STR_MACRO("Hello World!"));
// "foo" bar
使用 regex 排除包含字串的注釋行似乎效果很好^(?!\s*//).*"([^"] )"。但是,當我嘗試使用 regex 排除已經包含在宏中的未注釋字串時^(?!\s*//).*(?!STR_MACRO\()"([^"] )",它什么也不做(似乎是由于 STR_MACRO 之后的左括號)。
關于如何實作這一目標的任何提示?
uj5u.com熱心網友回復:
使用 PyPi 正則運算式模塊(您可以pip install regex在終端中安裝),您可以使用
import regex
pattern = r'''(?:^//.*|STR_MACRO\("[^"\\]*(?:\\.[^"\\]*)*"\))(*SKIP)(*F)|"[^"\\]*(?:\\.[^"\\]*)*"'''
text = r'''For instance, the regex should match the following strings:
std::cout << "Hello World!" << std::endl;
load_file("Hello World!");
But not the following ones:
std::cout << STR_MACRO("Hello World!") << std::endl;
load_file(STR_MACRO("Hello World!"));
// "foo" bar'''
print( regex.sub(pattern, r'STR_MACRO(\g<0>)', text, flags=regex.M) )
詳情:
(?:^//.*|STR_MACRO\("[^"\\]*(?:\\.[^"\\]*)*"\))(*SKIP)(*F)-//在行首和行的其余部分,或STR_MACRO(雙引號字串文字模式),然后跳過匹配,下一個匹配搜索從失敗位置開始|- 或者"[^"\\]*(?:\\.[^"\\]*)*"-",除 and 之外的零個或多個字符",\然后是 a 的零個或多個重復,\然后是任何單個字符,然后是除 a"和\chars 之外的零個或多個字符,然后是一個"char
請參閱Python 演示。輸出:
For instance, the regex should match the following strings:
std::cout << STR_MACRO("Hello World!") << std::endl;
load_file(STR_MACRO("Hello World!"));
But not the following ones:
std::cout << STR_MACRO("Hello World!") << std::endl;
load_file(STR_MACRO("Hello World!"));
// "foo" bar
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/475190.html
標籤:正则表达式
上一篇:failregex錯過條目
