gpt4 book ai didi

c++ - std regex_search 仅匹配当前行

转载 作者:行者123 更新时间:2023-11-30 05:09:37 27 4
gpt4 key购买 nike

我使用各种正则表达式逐行解析 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_bolregex_constants::match_not_eol 应该使 regex_search^$ 识别为仅行的开始/结束,而不是整个 block 的结束开始/结束。所以这是我的文件:

评论.cpp:

#include <stdio.h>
//comment

代码应该失败,我的逻辑是使用 regex_search 的那些选项,匹配应该失败,因为它应该在第一行搜索模式:

#include <stdio.h>

但它会搜索整个字符串,并立即找到 //comment。我需要帮助,使 regex_search 只匹配当前行。选项 match_not_bolmatch_not_eol 对我没有帮助。当然我可以在一个 vector 中逐行读取一个文件,然后对 vector 中的每个字符串进行所有规则的匹配,但是它很慢,我已经做到了,而且解析一个大文件需要很长时间那,这就是为什么我想让正则表达式处理新行,并使用定位计数器。

最佳答案

If it is not what you want please comment so I will delete the answer

您正在做的不是使用正则表达式库的正确方法。
因此,这是我对任何想要使用 std::regex 库的人的建议。

  1. 它只支持ECMAScript 不知何故有点比所有现代 regex 库都差。
  2. 它有多少你喜欢的错误(只是我发现的):

    1. the same regex but different results on Linux and Windows only C++
    2. std::regex and ignoring flags
    3. std::regex_match and lazy quantifier with strange behavior
  3. 在某些情况下(我专门使用 std::match_results 进行测试)与 std.regex 相比,它要慢 200 倍> 在 语言

  4. 它有非常困惑的标志匹配并且几乎不起作用(至少对我而言)

结论:根本不要使用它。


但如果有人仍然要求使用无论如何你可以:

  1. 使用boost::regex about Boost library 因为:

    1. PCRE支持
    2. 它的错误较少(我还没有看到)
    3. bin文件中比较小(编译后的可执行文件)
    4. 它比 std::regex 更快
  2. 使用 gcc 版本 7.1.0 并且如下。我发现的最后一个错误是版本 6.3.0

  3. 使用 clang 版本 3 或更高版本

如果您诱使(=说服)使用那么你可以使用:

  1. 使用 正则表达式 link 用于大型任务的库:std.regex 以及原因:

    1. 快速 Faster Command Line Tools in D
    2. 简单
    3. 灵活 drn
  2. 使用原生pcrepcre2 link 已写入

    • 非常快但有点复杂
  3. 使用对于一个简单的任务,特别是Perl one-liner link

关于c++ - std regex_search 仅匹配当前行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46087665/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com