【发布时间】:2012-02-11 18:31:39
【问题描述】:
假设我有一个 var std::string sourceCode; 我在其中加载了一个 cpp 源文件。现在我想从 tr1 中删除所有包含正则表达式类的 cmets(现在它们完全包含在内,因为我使用 Microsoft 编译器)- 单行很容易,但多行不是。这不仅仅是用空格等替换注释,而是要保持正确的行数。假设我们删除了一个 5 行长的注释,那么这个空间应该用 5 个换行符填充,以便我能够回溯代码并使用正确的行号进行计算。
到目前为止我的代码:
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
我确实不想激起 cmets 讨论使用 RegEx 来做这种事情是否有意义!请假设输入是干净且符合预期的。
【问题讨论】:
-
这并不像你想象的那么容易。考虑来源
string s = "not // a /* comment ..."; -
这是一个非常大胆的假设,考虑到您在问题中发布的代码会破坏您的正则表达式。
-
您可能需要执行一些翻译阶段。行延续在大多数其他内容甚至被 lexed 之前执行:codepad.org/LbarZgMg