Chinaunix首页 | 论坛 | 博客
  • 博客访问: 457434
  • 博文数量: 42
  • 博客积分: 1325
  • 博客等级: 中尉
  • 技术积分: 1312
  • 用 户 组: 普通用户
  • 注册时间: 2009-01-13 18:00
个人简介

呵~~~呵~~~

文章分类

全部博文(42)

文章存档

2016年(3)

2015年(1)

2014年(2)

2013年(2)

2012年(7)

2011年(11)

2010年(3)

2009年(13)

我的朋友

分类: LINUX

2009-04-18 20:54:24

例子1:
 

#include <stdio.h>
#include <string.h>
#include <pcre.h>

/**********************************************************************
*#include *
*parameters: src: string *
* pattern: regular expression *
*return: match >= 0 and nomatch < 0 *
*date: 2008-03-12 *
*developer: Leon *
**********************************************************************/

int fun_ismatch( char* src, char* pattern)
{
        pcre *re;
        const char *error;
        int erroffset;
        int rc;

        if( (re = pcre_compile( pattern, 0, &error, &erroffset, NULL)) == NULL) goto bad;
        if( (rc = pcre_exec( re, NULL, src, strlen(src), 0, 0, NULL, 0)) < 0) goto bad;

        free(re);
        return rc;
bad:
        free(re);
        return -1;
}

int main (int argc, char **argv)
{
        struct timeval tpstart,tpend;

        const char *pattern = "^*";
        argv[1] = "";

        gettimeofday( &tpstart, NULL);
        int result = fun_ismatch( argv[1], (char*)pattern);
        gettimeofday( &tpend, NULL);

        printf ("result: %d\nuse time: %u\n", result, tpend.tv_usec - tpstart.tv_usec);

        return;
}

 

例子2:

 

#include <stdio.h>
#include <string.h>
#include <pcre.h>
                
#define OVECCOUNT 30 /* should be a multiple of 3 */
#define EBUFLEN 128
#define BUFLEN 1024
        
int main()
{
        pcre *re;
        const char *error;
        int erroffset;
        int ovector[OVECCOUNT];
        int rc, i;
        
        char src [] = "111 Hello World 222";
        char pattern [] = "(.*)";
                
        printf("String : %s\n", src);
        printf("Pattern: \"%s\"\n", pattern);
        

        re = pcre_compile(pattern, 0, &error, &erroffset, NULL);
        if (re == NULL) {
                printf("PCRE compilation failed at offset %d: %s\n", erroffset, error);
                return 1;
        }

        rc = pcre_exec(re, NULL, src, strlen(src), 0, 0, ovector, OVECCOUNT);
        if (rc < 0) {
                if (rc == PCRE_ERROR_NOMATCH) printf("Sorry, no match ...\n");
                else printf("Matching error %d\n", rc);
                free(re);
                return 1;
        }

        printf("\nOK, has matched ...\n\n");

        for (i = 0; i < rc; i++) {
                char *substring_start = src + ovector[2*i];
                int substring_length = ovector[2*i+1] - ovector[2*i];
                printf("%2d: %.*s\n", i, substring_length, substring_start);
        }

        free(re);
        return 0;
}

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

上官寂伦2016-11-08 21:43:23

楼主 请问在内核态下用过pcre吗?

chinaunix网友2009-10-30 10:26:44

好贴。。。