c++ - 如何获取字符串中所有发现的 boost::regex 模式的位置?

标签 c++ regex gcc boost

我找不到它的工作代码,只能拼凑出这个片段,它编译但给出了错误的输出。

#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/

相关文章:

java - 用于密码验证的正则表达式第一个和最后一个字母不能有符号

regex - 如何使用正则表达式忽略以 0(零)开头的数字?

c++ - std::ofstream 构造函数阻塞

创建一个可以根据参数省略一行的宏

c++ - 等价于 C++ 中的 C NULL 函数指针?

objective-c - 正则表达式提取两个字符或标签之间的所有子字符串

c++ - 在 C++ 中将 AES 加密字符串转换为十六进制

Gcc 编译错误

c++ - Qmake错误: Unknown module(s) in QT: charts

c++ - 在 C++ 中链接非重叠、非连续的迭代器 (/boost)