如何迭代std :: string中的所有正则表达式匹配以及它们在c ++ 11 std :: regex中的起始位置?

rsk*_*k82 5 c++ regex gcc c++11

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

#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;
  }
}
Run Code Online (Sandbox Code Playgroud)

Cub*_*bbi 10

首先,为什么令牌迭代器?您没有任何标记的子表达式来迭代.

其次,position()是匹配的成员函数,因此:

#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';
    }
}
Run Code Online (Sandbox Code Playgroud)

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