std :: regex等效于'/g'全局修饰符 [英] std::regex equivalent of '/g' global modifier

查看:221
本文介绍了std :: regex等效于'/g'全局修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Perl中,我可以这样做:

In Perl, I can do this:

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

使用C ++正则表达式匹配,复制此行为的最佳方法是什么 我得到了包括所有火柴的火柴盒?

Using C++ regex matching, what's the best way to replicate this behaviour so that I get a match set including all the matches?

我现在有这个:-

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效果.

However this will only give me the first match, just like Perl without the /g which is fine, but I'd like the /g effect.

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

So, is there a good way to do it, or must I keep running the regex over and over?

推荐答案

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

You should call regex_search several times. Its return value specifies whether there are more matches. Each time you call it you get a new match. The iterator returned by results goes over the group submatches defined in your regular expression. The first entry is always the entire match, that's why in your case 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;
}

希望有帮助

这篇关于std :: regex等效于'/g'全局修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆