码迷,mamicode.com
首页 > 其他好文 > 详细

Boost::regex练习实例

时间:2015-01-28 17:24:44      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

    #include <algorithm>
    #include <vector>
    #include <string>
    #include <iostream>
    #include <cassert>
    #include <boost/regex.hpp>
    using namespace std;
    using namespace boost;
    //写一个程序,提取<p></p>之间的内容
    int main()
    {
        
    //  regex reg("(<p.*>(.*)</p>)?");
        regex reg("<p.*?>(.*?)</p>");
        vector<string> vec;
        string s= "<p>i‘m here!</p> and of course <pasda>you‘re here too,ok?</p>";
        sregex_iterator it(s.begin(),s.end(),reg);
        sregex_iterator end;
        while (it!=end)
        {
            vec.push_back((*it).str().c_str());
            it++;
        }
        copy(vec.begin(),vec.end(),ostream_iterator<string>(cout,"/n"));
        //在得到iterator或者子字符串后,再用regex_replace进行替换就行了。
        vector<string>   vec2;
        regex reg2("(<p.*?>)(.*?)(</p>)");
        for (vector<string>::iterator it3 = vec.begin();it3!=vec.end();it3++)
        {
            string s= *it3;
            s=regex_replace(s,reg2,"$2");
            vec2.push_back(s);
        }
        copy(vec2.begin(),vec2.end(),ostream_iterator<string>(cout,"/t"));
        return 0;
    }

 

直觉告诉我还可以写得更简洁一些,不过现在不够熟练,得慢慢琢磨了。

使用regex_iterator进行匹配,以及提取表达式,显得还不够熟练呢......正则表达式写错了,程序根本得不到想要的结果。

对于?的使用,应该有更进一步的认识了吧?

Boost::regex练习实例

标签:

原文地址:http://www.cnblogs.com/redhat520/p/4256292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!