假設我有一個var std::string sourceCode;
,我已經加載了一個cpp源文件。現在我想從tr1中刪除包含正則表達式類的所有註釋(現在它們完全包含在我使用的Microsoft編譯器中) - 單行很容易,但是多行不行。這不是僅僅用一個空格替換一個評論,而是要保持正確的行數。假設我們刪除了5行的註釋,那麼這個空間應該填充5個換行符,以便我能夠回溯代碼並使用正確的行號進行計算。用正則表達式剝離C++中的多行註釋
我迄今爲止代碼:
std::regex singleLinedCommentReg("//.*");
sourceCode = std::regex_replace(sourceCode, singleLinedCommentReg, std::string(""));
std::regex multiLinedCommentReg("(/\\*([^*]|[\r\n]|(\\*+([^*/]|[\r\n])))*\\*+/)");
std::for_each(
std::sregex_iterator(sourceCode.begin(), sourceCode.end(), multiLinedCommentReg),
std::sregex_iterator(),
[&](const std::match_results<std::string::const_iterator>& match) -> bool {
// TODO: Replace the current match with an appropriate number of newlines.
return true;
}
);
誰能給我上一些建議嗎?
編輯#1
我做不想挑起有關討論意見是否有意義使用正則表達式這種做的!請簡單地假設輸入是乾淨的並且如預期的那樣。
它並不像想象中那麼簡單。考慮源'string s =「not // a/* comment ...」;' – 2012-01-16 21:22:11
這是一個非常大膽的假設,考慮到您在問題中發佈的代碼會破壞您的正則表達式。 – Gerald 2012-01-16 21:30:11
您可能需要執行一些翻譯階段。在大多數其他任何事情都是lexed之前執行行延續:http://codepad.org/LbarZgMg – 2012-01-16 21:46:26