Chinaunix首页 | 论坛 | 博客
  • 博客访问: 580856
  • 博文数量: 158
  • 博客积分: 2696
  • 博客等级: 少校
  • 技术积分: 1668
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-10 00:49
个人简介

life?is?short?,?play?more!

文章分类

全部博文(158)

文章存档

2021年(1)

2013年(10)

2012年(4)

2011年(11)

2010年(27)

2009年(28)

2008年(52)

2007年(25)

我的朋友

分类: C/C++

2008-11-11 23:45:48

今天有人问关于c正则的问题,随把以前改的一段代码粘贴过来。由于当时设计的缘故,只能获得10个子匹配。(这个文件没有main函数,因为以前是作库开发的.)
 

#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <regex.h>//regular expresion head file here.
#include <string.h>

static char* _substr(const char *str,unsigned start, unsigned end)
{
    unsigned n = end - start;
    static char stbuf[256];
    strncpy(stbuf, str + start, n);
    stbuf[n] = 0;
    return stbuf;
}    

static int _match(char *pattern,char *str,char result[10][256])
{
    int x, z, cflags = 0;
    regex_t reg;
    regmatch_t pm[10];
    const size_t nmatch = 10;
    z = regcomp(&reg, pattern, cflags);
    if (z != 0)
    {
        printf("pattern error");;
        return -1;
    }
        if ((z = strlen(str)) > 0 && str[z-1]== '\n')
        {
            str[z - 1] = 0; //ascii code

        }
        z = regexec(&reg, str, nmatch, pm, 0);
        if (z == REG_NOMATCH)
        {
            return -2;
        }
        else if (z != 0)
        {
           regfree(&reg);//free

            return -3;
         }
         for (x = 1; x < nmatch && pm[x].rm_so!=-1; ++ x)
         {
              strcpy(result[x],_substr(str, pm[x].rm_so,pm[x].rm_eo));
         }
    /* free the reg */
    regfree(&reg);
    return 0;
}

/*a sample to use the regex match function . this function is used to verify the ipv4 format.*/
static int _validate_ip(char *ip )
{
  char match[10][256];
    if(strlen(ip) < 7 || strlen(ip) > 15){
         printf("ip format incorrect\n");
      return -1;
    }
/*由于\ 需要在c字符串里里转义,所以用到\需要用2个\\, 还有一个注意的是,c的正则表达式和通用的(perl,php)稍有区别。比如"." 代表一个任意字符,c里则是"\." ,请程序开发者需要自己注意。 */
  else if(_match("^[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+$",ip,match) != 0){
  printf("ip format incorrect \n");
    return -1;
    }    

  else{
  return 0;
  }

}

阅读(675) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~