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


我有一个字符串:

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

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

hello ([0-9]+)

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

(平台是视觉工作室2010,万一重要。)


4961
2018-04-07 19:48


起源



答案:


不要使用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;
}

13
2018-04-07 19:56



谢谢!比我想要的复杂一点,但这个例子确实有帮助。 - Colen


答案:


不要使用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;
}

13
2018-04-07 19:56



谢谢!比我想要的复杂一点,但这个例子确实有帮助。 - Colen