开发者

How do I use the new c++0x regex object to match repeatedly within a string?

I h开发者_JAVA技巧ave 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!

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


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.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜