c++ - 如何使用新的 c++0x regex 对象在字符串中重复匹配?

标签 c++ regex c++11

我有一个字符串:

"hello 1, hello 2, hello 17, and done!"

我想对它重复应用这个正则表达式:

hello ([0-9]+)

并且能够以某种方式遍历匹配项及其捕获组。我已经在 c++0x 中成功地使用了“正则表达式”来找到字符串中某物的第一个匹配项并检查捕获组的内容;但是,在找到所有匹配项之前,我不确定如何在字符串上多次执行此操作。帮助!

(平台是 visual studio 2010,以防万一。)

最佳答案

不要使用 regex_match,使用 regex_search。您可以在此处找到示例:http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15339 .

这应该可以解决问题(注意我是直接在浏览器中输入,没有编译它):

#include <iostream>
#include <regex>

int main()
{
   // regular expression
   const std::regex pattern("hello ([0-9]+)");

   // the source text
   std::string text = "hello 1, hello 2, hello 17, and done!";

   const std::sregex_token_iterator end;
   for (std::sregex_token_iterator i(text.cbegin(), text.cend(), pattern);
        i != end;
        ++i)
   {
      std::cout << *i << std::endl;
   }

   return 0;
}

关于c++ - 如何使用新的 c++0x regex 对象在字符串中重复匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5586733/

相关文章:

c++ - 矩阵 vector 乘法与 Eigen 系数乘积的结合

c++ 使用 cppunit 与 travis-ci.org 集成

php - 删除重复的尾部斜杠

c++ - Const 变量随 C 中的指针改变

c++ - 使用 BFS 的最短距离

Java Regex 屏蔽字母数字字符串并显示最后 4 位数字

regex - TCL 正则表达式从特定特殊字符中修剪字符串

c++ - 我如何指示 Emscripten 在编译期间应将源文件放置在何处?

regex - 我可以在 char16_t 字符串上使用 STL 正则表达式库吗?

c++ - boost::ref 没有发生匹配调用错误,但 std::ref 没有