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

       大概在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 
OperState
State


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值