如何循环遍历std::regex_search中的结果?

How do I loop through results from std::regex_search?

本文关键字:regex search 结果 std 何循环 循环 遍历      更新时间:2023-10-16

调用std::regex_search后,由于某种原因,我只能从std::smatch获得第一个字符串结果:

Expression.assign("rel="nofollow">(.*?)</a>");
if (std::regex_search(Tables, Match, Expression))
{
    for (std::size_t i = 1; i < Match.size(); ++i)
        std::cout << Match[i].str() << std::endl;
}

所以我试着用另一种方法——用迭代器:

const std::sregex_token_iterator End;
Expression.assign("rel="nofollow">(.*?)</a>");
for (std::sregex_token_iterator i(Tables.begin(), Tables.end(), Expression); i != End; ++i)
{
    std::cout << *i << std::endl;
}

这确实遍历每个匹配,但它也给了我整个匹配字符串,而不仅仅是我所追求的捕获。肯定有另一种方法,而不是在循环中的迭代器元素上做另一个std::regex_search ?

regex_token_iterator接受可选的第四个参数,指定每次迭代返回哪个子匹配。这个参数的默认值是0,在c++(和许多其他)正则表达式的情况下意味着"整个匹配"。如果想获得第一个捕获的子匹配,只需将1传递给构造函数:

const std::sregex_token_iterator End;
Expression.assign("rel="nofollow">(.*?)</a>");
for (std::sregex_token_iterator i(Tables.begin(), Tables.end(), Expression, 1); i != End; ++i)
{
    std::cout << *i << std::endl; // *i only yields the captured part
}

std::regex_search只搜索一次正则表达式。它不返回匹配列表,而是返回子匹配表达式列表(括号内的表达式)。这就是为什么你只得到一个Match[1],链接标签内的文本。

对于第二个代码,它实际上返回所有匹配项,但它返回的是match_results对象,因此您必须使用[]操作符:

const std::sregex_iterator End;
Expression.assign("rel="nofollow">(.*?)</a>");
for (std::sregex_iterator i(Tables.begin(), Tables.end(), Expression); i != End; ++i)
{
    std::cout << (*i)[1] << std::endl; // first submatch, same as above.
}