我找不到适合的工作代码,仅设法编写了该代码段,它可以编译但输出错误。

#include <string>
#include <iostream>
#include <boost/regex.hpp>
int main() {
  using namespace std;
  string input = "123 apples 456 oranges 789 bananas oranges bananas";
  boost::regex re = boost::regex("[a-z]+");
  boost::match_results<string::const_iterator> what;
  boost::match_flag_type flags = boost::match_default;
  string::const_iterator s = input.begin();
  string::const_iterator e = input.end();
  while (boost::regex_search(s,e,what,re,flags)){
    cout << what.position() << ", ";
    string::difference_type l = what.length();
    string::difference_type p = what.position();
    s += p + l;
  }
}

输出是:4, 5, 5, 1, 1,
但应为:4, 15, 27, 35, 43,

最佳答案

您几乎是正确的,但是没有考虑到cout << what.position() << ", ";将输出匹配字符串相对于最后一个匹配字符串(即s)末尾的位置这一事实。

由于s确切知道它相对于input的位置,因此应该可以:
cout << ((s - input.begin()) + what.position()) << ", ";

关于c++ - 如何获取字符串中所有boost::regex模式的已发现位置的位置?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23643634/

10-11 22:20
查看更多