#include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <regex.h>//regular expresion head file here. #include <string.h>
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; }
static int _match(char *pattern,char *str,char result[10][256]) { int x, z, cflags = 0; regex_t reg; regmatch_t pm[10]; const size_t nmatch = 10; z = regcomp(®, pattern, cflags); if (z != 0) { printf("pattern error");; return -1; } if ((z = strlen(str)) > 0 && str[z-1]== '\n') { str[z - 1] = 0; //ascii code
} z = regexec(®, str, nmatch, pm, 0); if (z == REG_NOMATCH) { return -2; } else if (z != 0) { regfree(®);//free
return -3; } for (x = 1; x < nmatch && pm[x].rm_so!=-1; ++ x) { strcpy(result[x],_substr(str, pm[x].rm_so,pm[x].rm_eo)); } /* free the reg */ regfree(®); return 0; }
/*a sample to use the regex match function . this function is used to verify the ipv4 format.*/ static int _validate_ip(char *ip ) { char match[10][256]; if(strlen(ip) < 7 || strlen(ip) > 15){ printf("ip format incorrect\n"); return -1; } /*由于\ 需要在c字符串里里转义,所以用到\需要用2个\\, 还有一个注意的是,c的正则表达式和通用的(perl,php)稍有区别。比如"." 代表一个任意字符,c里则是"\." ,请程序开发者需要自己注意。 */ else if(_match("^[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+$",ip,match) != 0){ printf("ip format incorrect \n"); return -1; }
else{ return 0; }
}
|