调用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
}

07-24 09:46
查看更多