/* 正则匹配
* 参数: buffer 需查找的范围
* pattern 正则匹配的模式
* start 匹配成功的字符串所在的相对偏移量起始位置
* end 匹配成功的字符串所在的相对偏移量结束位置
* 返回值: 1, 匹配
* 0, 不匹配
* -1, 出错
*/
int regex_match (char *buffer, char *pattern, regoff_t *start, regoff_t *end)
{
int match_ret = 0;
int status = 0;
int nmatch = 1;
int cflags = REG_EXTENDED | REG_ICASE | REG_NEWLINE;
int errcode = 0;
char err_buf[BUFF_SIZE] = {0};
regmatch_t pmatch[1];
regex_t reg;
if(NULL == buffer || NULL == pattern)
{
DEBUG_PRINT ("buffer or pattern NULL\n");
match_ret = OPERATE_FAIL;
goto label_ret;
}
if (0 != (errcode = regcomp(®, pattern, cflags)))
{
regerror (errcode, ®, err_buf, sizeof(err_buf));;
DEBUG_PRINT ("Error while regcomp: %s\n", err_buf);
match_ret = OPERATE_FAIL;
goto label_ret;
}
status = regexec(®, buffer, nmatch, pmatch, 0);
if(REG_NOMATCH == status)
{
match_ret = REGEX_NOMATCH;
goto label_ret;
}
else if(0 == status)
{
match_ret = REGEX_MATCH;
*start = pmatch[0].rm_so;
*end = pmatch[0].rm_eo;
goto label_ret;
}
else
{
DEBUG_PRINT ("regexec() error!\n");
match_ret = OPERATE_FAIL;
goto label_ret;
}
label_ret:
if (0 == errcode)
{
regfree(®);
}
return match_ret;
}
正则匹配实例
最新推荐文章于 2021-11-23 11:58:36 发布