如何在字符串中获得boost::regex模式的所有发现的位置
how to get positions of all found occurences of a boost::regex pattern in a string?
我找不到有效的代码,只能创建这个代码片段,它编译但给出错误的输出。
#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()) << ", ";
相关文章:
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 为什么在保护模式下继承升级不起作用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 此模式的C++RegEx
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 使用可变模板的Broadcaster/Listener模式
- c++方法参数只能在linux的发布模式下自行更改
- 资源管理设计模式
- 使用 mod_gsoap 部署服务时,如何在 Gsoap 中更改 soap 上下文的模式?
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 小字符串优化(调试与发布模式)
- 可视化C++:发布模式的运行时库作为'Multi-threaded Debug DLL'
- 将Javascript正则表达式模式转换为C++std::regex的规则
- c++ std::regex, smatch在模式字符串中只保留一次子表达式
- 如何忽略c++ regex中记号之间的空白(自由空格模式)
- 为什么我得到两个不同的结果,而使用sregex_iterator与regex变量模式vs构造模式
- 如何在字符串中获得boost::regex模式的所有发现的位置
- 从std::regex中提取原始regex模式