将所有正则表达式匹配项保存在向量上
Save all regex matches on a vector
因此,我需要创建一个函数,该函数基于正则表达式获取一个字符串上的所有匹配项,然后将它们存储在数组中,以最终在单个匹配项中选择任意捕获组编号。我试过这个:
std::string match(std::string basestring, std::string regex, int index, int group) {
std::vector<std::smatch> match;
(here I would need to create a while statement that iterates over all matches, but I'm not sure what overload of 'regex_search' I have to use)
return match.at(index)[group]; }
我想得到一个匹配项,然后开始在该匹配项的结束位置旁边搜索,以便获得下一个匹配项,当找不到匹配项时,我们假设没有更多的匹配项,因此 while 语句结束,然后索引和组参数将在匹配项中获得所需的捕获组。但我似乎找不到需要开始(或开始和结束(位置以及需要目标字符串的"regex_search"重载。
经过几个小时的挖掘,我自己找到了解决方案,这段代码将完成这项工作:
std::string match(std::string s, std::string r, int index = 0, int group = 0) {
std::vector<std::smatch> match;
std::regex rx(r);
auto matches_begin = std::sregex_iterator(s.begin(), s.end(), rx);
auto matches_end = std::sregex_iterator();
for (std::sregex_iterator i = matches_begin; i != matches_end; ++i) { match.push_back(*i); }
return match.at(index)[group]; }
相关文章:
- C++模板来检查友元函数的存在
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 既然存在危险,为什么项目要使用-I include开关
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 我们可以访问一个不存在的联盟的成员吗
- C++:对不存在的命名空间使用命名空间指令
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- EvtExportLogneneneba API正在将远程计算机的事件日志保存到远程PC本身.如何将其保存到主机
- C++quit()函数中可能存在作用域问题
- C++擦除(如果存在)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 使用导入的图像保存在 QT 中的 QLabel 中,保存 GUI 的状态
- 阵列不能两次将相同的名称保存,当要添加新字符串时,程序应检查以查看该名称是否已经存在
- 方法,该方法调用所有基类的同名方法(如果存在),并将返回值保存到列表中
- 什么设计模式将数据部分保存在持久存储 (SQL) 中,部分保存在 RAM(内存)中
- 是否存在可用于保存任何枚举值的整型?
- 将对象指针保存在 STL 容器中是否比将对象本身保存更好
- 从控制台保存信息,然后重新打开时,信息仍然存在