zoukankan      html  css  js  c++  java
  • c语言 正则表达式 IP地址

     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] = '';
    57 printf("match: %s
    ", matched);
    58 }
    59 
    60 regfree(&re);   /* 用完了别忘了释放 */
    61 return (0);
    62 }
    View Code
  • 相关阅读:
    input file 多张图片上传 获取地址 ——fileReader
    15个常用的javaScript正则表达式
    sublime-emmet
    AMD-requireJS
    jQuery-lazyload参数
    easyui 查询条件form 数据遍历
    导出excel设置金额格式
    html5页面添加时间戳
    创建枚举
    定义实体转json需要方法
  • 原文地址:https://www.cnblogs.com/tianciliangen/p/3410088.html
Copyright © 2011-2022 走看看