如何循环遍历std::regex_search中的结果?
How do I loop through results from std::regex_search?
调用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.
}
相关文章:
- 此模式的C++RegEx
- QTableview Search
- LeetCode 1011.Binary Search,C++和Python的想法相同,但输出不同
- C++ std::regex 使用前瞻失败
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 二叉搜索树 - 实现"search"函数
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- 使用Regex解析cpp中的字符串并创建映射
- C++:如何用split查找单词?Regex
- 在VC2015U3上,std::regex比boost::regex慢得多
- 是否有更有效的方法来生成日期的REGEX字符串
- 在C++中使用带有regex的捕获组
- 将std::regex设置为静态的好主意吗
- 为什么Regex(c++)需要指数时间
- std::regex and dual ABI
- C++11 std::regex后备选项
- 以不同的方式替换每一项,regex c++
- 使用 boost::regex (c++) 比较两个正则表达式
- 如何理解boost::regex的哪一部分未能匹配/search