如何循环通过std :: regex_search的结果? [英] How do I loop through results from std::regex_search?
问题描述
调用 std :: regex_search
后,我只能从 std :: smatch $ c获取第一个字符串结果$ c>由于某种原因:
After calling std::regex_search
, I'm only able to get the first string result from the std::smatch
for some reason:
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;
}
所以我试着用另一种方法 - 使用迭代器:
So I tried to do it another way - with an iterator:
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
?
This does go through every match, but it also gives me the whole matching string instead of just the capture that I was after. Surely must be another way than having to do another std::regex_search
on the iterator element in the loop?
提前感谢。
推荐答案
regex_token_iterator
每次迭代都返回子匹配。此参数的默认值为0,在C ++(和许多其他)正则表达式的情况下意味着整个匹配。如果你想得到第一个捕获的submatch,只需传递1到构造函数:
regex_token_iterator
takes an optional fourth argument specifying which submatch is returned for each iteration. The default value of this argument is 0, which in case of the C++ (and many other) regexes means "the whole match". If you want to get the first captured submatch, simply pass 1 to the constructor:
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的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!