我使用各种正则表达式逐行解析 C 源文件。首先我读取字符串中文件的所有内容:
ifstream file_stream("commented.cpp",ifstream::binary);
std::string txt((std::istreambuf_iterator<char>(file_stream)),
std::istreambuf_iterator<char>());
然后我使用一组正则表达式,它应该连续应用,直到找到匹配,这里我只给出一个示例:
vector<regex> rules = { regex("^//[^\n]*$") };
char * search =(char*)txt.c_str();
int position = 0, length = 0;
for (int i = 0; i < rules.size(); i++) {
cmatch match;
if (regex_search(search + position, match, rules[i],regex_constants::match_not_bol | regex_constants::match_not_eol))
{
position += ( match.position() + match.length() );
}
}
但这不起作用。它将匹配不在当前行中的注释,但它将搜索整个字符串,以查找第一个匹配项,regex_constants::match_not_bol
and regex_constants::match_not_eol
应该使regex_search
去辨认^$
仅作为行的开始/结束,而不是整个块的结束开始/结束。这是我的文件:
评论.cpp:
#include <stdio.h>
//comment
代码应该失败,我的逻辑是使用 regex_search 的这些选项,匹配应该失败,因为它应该在第一行搜索模式:
#include <stdio.h>
但它会搜索整个字符串,并立即找到//comment
。我需要帮助,使regex_search
仅在当前行匹配。选项match_not_bol
and match_not_eol
不要帮助我。当然,我可以在向量中逐行读取文件,然后对向量中每个字符串的所有规则进行匹配,但是它非常慢,我已经这样做了,并且解析像这样的大文件需要很长时间这就是为什么我想让正则表达式处理新行并使用定位计数器。