std :: regex等效于\'/ g\'全局修饰符

问题描述

|| 在Perl中,我可以这样做:
$text = \'1747239\';
@matches = ($text =~ m/(\\d)/g);
# @matches Now contains (\'1\',\'7\',\'4\',\'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效果。 因此,有什么好方法吗?还是我必须不断地运行正则表达式?     

解决方法

您应该多次拨打
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;
}
希望能帮助到你