函数
/************************************
*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;
}