分类: C/C++
2006-12-30 10:24:24
#include
#include
#include
#include
static char* SubStr(const char* str,unsigned start,unsigned end)
{
unsigned n=end-start;
static char stbuf[256];
strncpy(stbuf,str+start,n);
stbuf[n]=0;
return stbuf;
}
int main(int argc,char** argv)
{
if(argc<3)
{
printf("Parameters are not enough !!!\n");
printf("Usage: TestRegExp
return -1;
}
const char* pRegExpString=argv[1]; //正则表达式字符串
const char* String=argv[2]; //需要匹配的字符串
char ebuf[128]; //存放错误信息
regmatch_t pmatch[10]; //存放匹配结果的数组
const size_t nmatch=10; //所允许的最多的匹配数量
int x=0;
regex_t CRegExp;
int RegCompRet,RegExecRet;
RegCompRet=regcomp(&CRegExp,pRegExpString,0);
if(RegCompRet!=0)
{
regerror(RegCompRet,&CRegExp,ebuf,sizeof(ebuf));
printf("%s: pattern '%s' \n",ebuf,pRegExpString);
return -2;
}
RegExecRet=regexec(&CRegExp,String,nmatch,pmatch,0);
if(RegExecRet==REG_NOMATCH)
{
printf("Not Match\n");
regfree(&CRegExp);
return -3;
}
else if(RegExecRet!=0)
{
regerror(RegExecRet,&CRegExp,ebuf,sizeof(ebuf)) ;
printf("%s: '%s'",ebuf,pRegExpString);
return -4;
}
else
//输出匹配结果
printf("Match:\n");
for(x=0;x
printf("%d: %s\n",x+1,SubStr(String,pmatch[x].rm_so,pmatch[x].rm_eo));
//printf("Start:%d End:%d\n",pmatch[0].rm_so,pmatch[0].rm_eo);
}
//释放正则表达式
regfree(&CRegExp);
return 0;
}