#include
#include
#include
#include
//对输入的模式与待匹配的字符串进行匹配;成功返回0;
//pattern : 模式
// buf : 待匹配的字符串;
int regexp(char *pattern, char * buf)
{
regex_t reg;
int status = 0;
int cflags = REG_EXTENDED|REG_NOSUB;
char error[32];
/* 编译正则表达式*/
status = regcomp (®, pattern, cflags);
if (status != 0)
{
regerror(status, ®, error, sizeof(error));
printf("regcomp ERROR -> %s: pattern '%s'\n", pattern, error);
return -1;
}
//进行匹配
status = regexec(®, buf, 0, NULL, 0);
if(status != 0)
{
if(status != REG_NOMATCH)
{
regerror(status, ®, error, sizeof(error));
printf("regexec -> NON REG_NOMATCH -> ERROR -> status = %d: '\n", error);
status = -2;
}
else if(status == REG_NOMATCH)
{
printf("regexec -> REG_NOMATCH -> ERROR -> status = %d: '\n", error);
status = -3;
}
}
else
{
printf("regexec -> REG_NOMATCH -> SUCCESS -> pattern = %s, buf = %s \n", pattern, buf);
status = 0;
}
/* 输出处理结果 */
//如果有必要可以输出匹配的结果;
/* 释放正则表达式 */
regfree(®);
//返回处理结果;
return status;
}
/* 主程序 */
int main(int argc, char** argv)
{
//char * pattern = "^[0-9]*[1-9][0-9]*$";
char *pattern = "^[0-9]+$";
//char *pattern = "^\\d+$";
char *buf = "00000";
int a = regexp(pattern, buf);
printf("main -> INFO -> a = %d \n", a);
}
注:不支持正则表达式的控制。