1 #include <stdio.h> 2 #include <string.h> 3 #include <regex.h> 4 5 #define SUBSLEN 10 /* 匹配子串的数量 */ 6 #define EBUFLEN 128 /* 错误消息buffer长度 */ 7 #define BUFLEN 1024 /* 匹配到的字符串buffer长度 */ 8 9 int main() 10 { 11 size_t len; 12 regex_t re; /* 存储编译好的正则表达式,正则表达式在使用之前要经过编译 */ 13 regmatch_t subs [SUBSLEN]; /* 存储匹配到的字符串位置 */ 14 char matched [BUFLEN]; /* 存储匹配到的字符串 */ 15 char errbuf [EBUFLEN]; /* 存储错误消息 */ 16 int err, i; 17 18 char src [] = "sdafsdfsdf52.23.11.43sdafsdfsdfasdfa"; /* 源字符串 */ 19 char pattern [] = "([0-9]{1,3}[.]){3}[0-9]{1,3}"; /* pattern字符串 */ 20 21 printf("String : %s ", src); 22 printf("Pattern: "%s" ", pattern); 23 24 /* 编译正则表达式 */ 25 err = regcomp(&re, pattern, REG_EXTENDED); 26 27 if (err) { 28 len = regerror(err, &re, errbuf, sizeof(errbuf)); 29 printf("error: regcomp: %s ", errbuf); 30 return 1; 31 } 32 printf("Total has subexpression: %d ", re.re_nsub); 33 /* 执行模式匹配 */ 34 err = regexec(&re, src, (size_t) SUBSLEN, subs, 0); 35 36 if (err == REG_NOMATCH) { /* 没有匹配成功 */ 37 printf("Sorry, no match ... "); 38 regfree(&re); 39 return 0; 40 } else if (err) { /* 其它错误 */ 41 len = regerror(err, &re, errbuf, sizeof(errbuf)); 42 printf("error: regexec: %s ", errbuf); 43 return 1; 44 } 45 46 /* 如果不是REG_NOMATCH并且没有其它错误,则模式匹配上 */ 47 printf(" OK, has matched ... "); 48 for (i = 0; i <= re.re_nsub; i++) { 49 len = subs[i].rm_eo - subs[i].rm_so; 50 if (i == 0) { 51 printf ("begin: %d, len = %d ", subs[i].rm_so, len); /* 注释1 */ 52 } else { 53 printf("subexpression %d begin: %d, len = %d ", i, subs[i].rm_so, len); 54 } 55 memcpy (matched, src + subs[i].rm_so, len); 56 matched[len] = '