C語言處理Regex常用的函數有regcomp()、regexec()、regfree()和regerror(),
C語言中使用Regex一般分為三步:
編譯Regex regcomp()
匹配Regex regexec()
釋放Regex regfree()
本篇文章主要是通過regcomp()、regexec()、regerror()、regfree()函數在c中的應用,複習Regex的用法。
程式一、email地址驗證:
[cpp] view plain copy #include <stdio.h> #include <sys/types.h> #include <regex.h> int main(int argc,char * argv) { int status,i; int cflags=REG_EXTENDED; regmatch_t pmatch[1]; const size_t nmatch=1; regex_t reg; const char *pattern="^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*.\\w+([-.]\\w+)*$"; char *buf="sdlcwangsong@sina.cn"; regcomp(®,pattern,cflags); status=regexec(®,buf,nmatch,pmatch,0); if(status==REG_NOMATCH) printf("No Match\n"); else if(status==0){ printf("Match:\n"); for(i=pmatch[0].rm_so;i<pmatch[0].rm_eo;i++) putchar(buf[i]); printf("\n"); } regfree(®); return 0; }
其中驗證email地址的Regex為:
運算式可以分為圖中所示幾部分,下面分別解釋:
^:表示匹配的起始位置
\w+:表示字母底線數字出現一次或多次
([-.]\w+)* 表示-號 .號 字母 數字 底線 出現零次或多次
*:表示這裡可以跟任意個任一字元
.:表示固定的一個"."
$:表示匹配的結束位置
程式執行後的匹配結果:
程式二、IP地址驗證:
[cpp] view plain copy #include <stdio.h> #include <sys/types.h> #include <regex.h> int main(int argc,char * argv) { int status,i; int cflags=REG_EXTENDED; regmatch_t pmatch[1]; const size_t nmatch=1; regex_t reg; const char *pattern="^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9]).){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$";
char *buf="192.68.16.39"; regcomp(®,pattern,cflags); status=regexec(®,buf,nmatch,pmatch,0);