如何在c ++ 11 std :: regex中以其开始位置迭代std :: string中的所有正则表达式匹配项? [英] how to iterate all regex matches in a std::string with their starting positions in c++11 std::regex?

查看:221
本文介绍了如何在c ++ 11 std :: regex中以其开始位置迭代std :: string中的所有正则表达式匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道两种从std :: string获取正则表达式匹配项的方法,但我不知道如何获取所有具有各自偏移量的匹配项。

I know two ways of getting regex matches from std::string, but I don't know how to get all matches with their respective offsets.

#include <string>
#include <iostream>
#include <regex>
int main() {
  using namespace std;
  string s = "123 apples 456 oranges 789 bananas oranges bananas";
  regex r = regex("[a-z]+");
  const sregex_token_iterator end;
  // here I know how to get all occurences
  // but don't know how to get starting offset of each one
  for (sregex_token_iterator i(s.cbegin(), s.cend(), r); i != end; ++i) {
    cout << *i << endl;
  }
  cout << "====" << endl;
  // and here I know how to get position
  // but the code is finding only first match
  smatch m;
  regex_search ( s, m, r );
  for (unsigned i=0; i< m.size(); ++i) {
    cout << m.position(i) << endl;
    cout << m[i] << endl;
  }
}


推荐答案

第一个首先,为什么要使用令牌迭代器?您没有要迭代的任何标记子表达式。

First of all, why token iterator? You don't have any marked subexpressions to iterate over.

第二, position()是比赛的成员函数,因此:

Second, position() is a member function of a match, so:

#include <string>
#include <iostream>
#include <regex>
int main() {
    std::string s = "123 apples 456 oranges 789 bananas oranges bananas";
    std::regex r("[a-z]+");

    for(std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r);
                            i != std::sregex_iterator();
                            ++i )
    {
        std::smatch m = *i;
        std::cout << m.str() << " at position " << m.position() << '\n';
    }
}

在coliru居住: http://coliru.stacked-crooked.com/a/492643ca2b6c5dac

live at coliru: http://coliru.stacked-crooked.com/a/492643ca2b6c5dac

这篇关于如何在c ++ 11 std :: regex中以其开始位置迭代std :: string中的所有正则表达式匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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