如何在字符串中获得boost::regex模式的所有发现的位置

how to get positions of all found occurences of a boost::regex pattern in a string?

本文关键字:regex 模式 位置 发现 boost 字符串      更新时间:2023-10-16

我找不到有效的代码,只能创建这个代码片段,它编译但给出错误的输出。

#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()) << ", ";