gpt4 book ai didi

c++ - 将所有正则表达式匹配保存在 vector 上

转载 作者:太空宇宙 更新时间:2023-11-04 12:47:00 28 4
gpt4 key购买 nike

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

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语句结束,那么 index 和 group 参数将在匹配中获得所需的捕获组。但我似乎找不到需要起始(或起始和结束)位置以及需要目标字符串的“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++ - 将所有正则表达式匹配保存在 vector 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50997432/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com