如何使用新的c ++ 0x regex对象在字符串中重复匹配? [英] How do I use the new c++0x regex object to match repeatedly within a string?

查看:142
本文介绍了如何使用新的c ++ 0x regex对象在字符串中重复匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:

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

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

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

hello ([0-9]+)

并且能够通过匹配和他们的捕获组不断地迭代。我在c ++ 0x中成功使用了正则表达式的东西来找到字符串中第一个匹配的东西,并检查捕获组的内容;然而,我不知道如何多次对一个字符串,直到找到所有的匹配,这样做。帮助!

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,万一有问题。)

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

推荐答案

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

这篇关于如何使用新的c ++ 0x regex对象在字符串中重复匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆