C Language Processing regular expressions commonly used functions are Regcomp (), Regexec (), RegFree () and Regerror (),
The use of regular expressions in the C language is generally divided into three steps:
Compiling regular expression Regcomp ()
Match Regular Expression regexec ()
Free Regular Expression RegFree ()
This article is mainly to review the use of regular expressions through the application of Regcomp (), Regexec (), Regerror (), RegFree () function in C.
Program one, email address verification:
[CPP] View plain copy #include <stdio.h> #include <sys/types.h> #include <regex.h> int main (INT&NBSP;ARGC,CHAR&NBSP;*&NBSP;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; }
The regular expression in which the email address is validated is:
The expression can be divided into several sections shown in the diagram, which are explained separately below:
^: Indicates the starting position of the match
\w+: Indicates that a letter underline number occurs one or more times
([-.] \w+) * denotes-number. Alphanumeric underline occurs 0 or more times
*: means that you can follow any character here
.: Represents a fixed "."
$: Indicates a matching end position
Match results after program execution:
Program two, IP address verification:
[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);