将所有正则表达式匹配项保存在向量上

Save all regex matches on a vector

本文关键字:保存 存在 向量 正则表达式      更新时间:2023-10-16

因此,我需要创建一个函数,该函数基于正则表达式获取一个字符串上的所有匹配项,然后将它们存储在数组中,以最终在单个匹配项中选择任意捕获组编号。我试过这个:

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]; }
相关文章: