C中使用Regex驗證email地址和IP地址__Regex

來源:互聯網
上載者:User

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(&reg,pattern,cflags);       status=regexec(&reg,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(&reg);       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(&reg,pattern,cflags);       status=regexec(&reg,buf,nmatch,pmatch,0);  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.