自己用C++写的简单正则,以后慢慢完善扩充成为一个合格的正则

函数

/************************************
*Function:_Regular(const std::string strSource,const std::string strRegular,std::vector<std::string> &vecResult)
*author:songbin.sky@gmail.com
*date:2013-04-11
*parameter:
*         input->
*               strSource:原字符串
*               strRegular:正则表达式,目前只匹配(*)类型。不能同时匹配两个以及以上的正则.
*               vecResult:返回结果存储的向量
*description:自己实现一个简单的正则
**************************/
bool _Regular(const std::string strSource,const std::string strRegular,std::vector<std::string> &vecResult)
{
	  std::string strStart;
	  std::string strEnd;
	  std::string::size_type nPos = strRegular.find("*");
	  std::string::size_type nCurrentPos=0;
	  std::string::size_type nStartPos;
	  std::string::size_type nEndPos;
	  if(std::string::npos == nPos)
	  {
	  	std::cout<<"Parse Regular failed"<<std::endl;
	  	return false;	
	  }
	  strStart = strRegular.substr(0,nPos);
	  strEnd   = strRegular.substr(nPos+1,strRegular.size()-1-nPos);
	  std::cout<<"start->  "<<strStart<<std::endl<<"end->  "<<strEnd<<std::endl;
	  
	  nStartPos = strSource.find(strStart.c_str(),nCurrentPos);
	  while(std::string::npos != nStartPos)
	  {
	  		
	  		nEndPos = strSource.find(strEnd.c_str(),nStartPos+strStart.size());
	  		if(std::string::npos == nEndPos||nEndPos==(nStartPos+strStart.size())) 
	  		{
	  			  std::cout<<"nEndPos:"<<nEndPos<<"\nnStartPos:"<<nStartPos<<"\nstrStart.size():"<<strStart.size()<<std::endl;
	  				break;
	  		}
	  		std::string strValue = strSource.substr(nStartPos+strStart.size(),nEndPos-nStartPos-strStart.size());
	  		//std::cout<<strValue<<std::endl;
	  		vecResult.push_back(strValue);
	  		nCurrentPos=nEndPos+strEnd.size();
	  		nStartPos = strSource.find(strStart.c_str(),nCurrentPos);
	  }
	  if(vecResult.empty()) return false;
		return true;
}

完整示例

#include<iostream>
#include<vector>
bool _Regular(const std::string strSource,const std::string strRegular,std::vector<std::string> &vecResult);
int main(int argc,char **argv)
{
	  std::string Regular = "%%*%%";
		std::string str="3213([%%aa%%])32131%%23%%([bb])%%434%%([cc])"; 
		std::vector<std::string> Result;
	  bool bResult = _Regular(str,Regular,Result);
	  std::cout<<"Original string is : "<<str<<std::endl;
	  if(bResult)
	  {
	  	for(std::vector<std::string>::iterator it=Result.begin();it!=Result.end();it++)
	  	{
	  		std::cout<<it->c_str()<<std::endl;	
	  	}
	  }
	  else
	  {
	  	std::cout<<"result is null"<<std::endl;	
	  }
	  return 0;	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值