使用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
- 使用C++实现简单的正则表达式
- c实现极简单的正则表达式解析
- 简单的正则表达式实现
- 正则表达式的简单使用
- 正则表达式的简单使用
- 正则表达式的简单使用
- 正则表达式的简单使用
- 使用正则表达式实现一个简单的QQ登录验证
- 正则表达式的使用(C++)
- 实现最简单的正则表达式
- 简单功能的正则表达式引擎实现
- 简单正则表达式匹配的Java实现
- 正则表达式---简单使用
- 正则表达式简单使用
- ABAP中正则表达式的简单使用
- Java中正则表达式的简单使用
- ABAP中正则表达式的简单使用
- ABAP中正则表达式的简单使用
- HDU 4534 郑厂长系列故事——新闻净化(AC自动机+DP)
- java.lang.NoSuchMethodError找不到方法,但是那个方法明明存在
- javascript小结:对象
- Thunk 技术的一个改进
- int string CStirng的相互装换
- 使用C++实现简单的正则表达式
- C++及Windows异常处理(try,catch; __try,__finally; __try, __except)
- 完整的游戏数据包下载安装教程
- sizeof strlen length 之区别
- hdu 1394 Minimum Inversion Number(线段树 单点更新)
- SCI与SPI区别
- 第一节:准备工作
- 【联大CSDN第一期】IT职业发展规划
- Jquery学习集锦