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

时间:2022-09-13 12:07:36

I have a string:

我有一个字符串:

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

And I want to apply this regular expression repeatedly to it:

我想把这个正则表达式反复地应用到它上面:

hello ([0-9]+)

And be able to iterate through the matches and their capture groups somehow. I've used the "regex" stuff successfully in c++0x to find the first match for something in a string and inspect the contents of the capture group; however, I'm not sure how to do this multiple times on a string until all the matches are found. Help!

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

(Platform is visual studio 2010, in case it matters.)

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

1 个解决方案

#1


13  

Don't use regex_match, use regex_search. You can find examples here: http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15339.

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

This should do the trick (notice I'm typing directly in the browser, didn't compile it):

这应该很有用(注意,我直接在浏览器中输入,没有编译):

#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;
}

#1


13  

Don't use regex_match, use regex_search. You can find examples here: http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15339.

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

This should do the trick (notice I'm typing directly in the browser, didn't compile it):

这应该很有用(注意,我直接在浏览器中输入,没有编译):

#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;
}