使用C++实现简单的正则表达式

来源:互联网 发布:java微信客服接口开发 编辑:程序博客网 时间:2024/05/29 14:04

       大概在1年多前,那个时候我才刚毕业一年多一点的时间。那个时候精力很是旺盛,每天在公司加班到10点回去还要自己鼓捣点东西。有段时间鼓捣了一个天涯论坛阅读器,实现了不用登录帐号即可实现“只看楼主”功能。在那个小玩具软件里面需要大量过滤网页文本内容,所以就写了一个小函数实现了类似于正则表达式的功能。


       没想到当年写的这个函数,现在在项目中竟然用到了。好吧,那说明这个函数还是有一定实用价值的。那么就共享出来吧。

      

int preg_match_all(const std::string source,std::string strStart,std::string strEnd,std::vector<std::string> &strDest){        std::string strSource = source;        std::string nStrItem;;        int cnt=0;        std::string::size_type nPos_s = strSource.find(strStart);        std::string::size_type nPos_e = strSource.find(strEnd);        while(nPos_s != std::string::npos && nPos_e != std::string::npos && nPos_s<nPos_e)        {                cnt++;                 nStrItem = strSource.substr(nPos_s+strStart.size(),nPos_e-nPos_s-strStart.size());                strDest.push_back(nStrItem);                strSource = strSource.erase(0,nPos_e+strEnd.size());                 nPos_s = strSource.find(strStart);                nPos_e = strSource.find(strEnd);        }        return cnt;}
     上面这个是函数的实现,下面的是完整可以跑起来的CPP文件源码

    

#include <iostream>#include <vector>int preg_match_all(const std::string source,std::string strStart,std::string strEnd,std::vector<std::string> &strDest);int main(int argc,char **argv){    char str[]="[异常] {OperState}!= UP & {State} != UP";    char S[]="{";    char E[]="}";    std::vector<std::string> Dest;    preg_match_all(str,S,E,Dest);    for(std::vector<std::string>::iterator it=Dest.begin();it!=Dest.end();it++)    {       std::cout<<it->c_str()<<std::endl;    }    return 0;}int preg_match_all(const std::string source,std::string strStart,std::string strEnd,std::vector<std::string> &strDest){        std::string strSource = source;        std::string nStrItem;;        int cnt=0;        std::string::size_type nPos_s = strSource.find(strStart);        std::string::size_type nPos_e = strSource.find(strEnd);        while(nPos_s != std::string::npos && nPos_e != std::string::npos && nPos_s<nPos_e)        {                cnt++;                 nStrItem = strSource.substr(nPos_s+strStart.size(),nPos_e-nPos_s-strStart.size());                strDest.push_back(nStrItem);                strSource = strSource.erase(0,nPos_e+strEnd.size());                 nPos_s = strSource.find(strStart);                nPos_e = strSource.find(strEnd);        }        return cnt; }
早fedora下运行结果如下:

[root@localhost test]# g++ hello.cpp [root@localhost test]# ./a.out OperStateState


原创粉丝点击