【问题标题】:std::regex equivalent of '/g' global modifierstd::regex 等效于 '/g' 全局修饰符
【发布时间】:2011-09-02 11:06:13
【问题描述】:

在 Perl 中,我可以这样做:

$text = '1747239';
@matches = ($text =~ m/(\d)/g);
# @matches now contains ('1', '7', '4', '7', '2', '3', '9')

使用 C++ 正则表达式匹配,复制这种行为的最佳方法是什么? 我得到一个包含所有匹配项的匹配集?

我现在有这个:-

compiledRegex = std::regex(regex, std::tr1::regex_constants::extended);
regex_search(text, results, compiledRegex);

int count = results.size();
// Alloc pointer array based on count * sizeof(mystruct).
for ( std::cmatch::iterator match = results.begin(); 
      match != results.end(); 
      ++match )
{
    // Do something with match;
}

但是这只会给我第一个匹配,就像没有 /g 的 Perl 一样,这很好,但我想要 /g 效果。

那么,有什么好的方法可以做到吗,还是我必须一遍又一遍地运行正则表达式?

【问题讨论】:

    标签: c++ regex tr1


    【解决方案1】:

    您应该多次致电regex_search。它的返回值指定是否有更多的匹配。每次你调用它,你都会得到一个新的匹配。结果返回的迭代器遍历正则表达式中定义的组子匹配。第一个条目总是整个匹配,这就是为什么在你的情况下count == 1

    std::string::const_iterator text_iter = text.cbegin();
    compiledRegex = std::regex(regex, std::tr1::regex_constants::extended);
    
    while (regex_search(text_iter, text.end(), results, compiledRegex))
    {
        int count = results.size();
        // Alloc pointer array based on count * sizeof(mystruct).
        for ( std::cmatch::iterator group = results.begin();
              group != results.end();
              ++group )
        {
            // If you uses grouping in your search here you can access each group
        }
    
       std::cout << std::string(results[0].first, results[0].second) << endl;
       text_iter = results[0].second;
    }
    

    希望对你有帮助

    【讨论】:

    • 这几乎就是我想要做的,我想我希望有一个标志来让 regex_search 做到这一点。大概您需要将文本指针移动到每次迭代的最后一个匹配项的末尾?
    • @JonB 你是对的。应该使用迭代器而不是字符串。在每次迭代结束时,应该使用results[0].second 更新搜索迭代器。我已经更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 2013-10-04
    • 2010-10-20
    • 2011-02-15
    相关资源
    最近更新 更多