C语言正则表达式库pcre介绍

最强大的C语言正则表达式库pcre
2009-05-24 23:18
PCRE - Perl Compatible Regular Expressions
主页下载:http://www.pcre.org/
在ubuntu下编译安装:
1: ./configure
2: make
3: make install


此三步即可安装成功,安装成功后的头文件在:/usr/local/include, 库文件在:/usr/local/lib

不多说了,下面是一个例子程序,自己去领悟吧。
#include <stdio.h>
#include <string.h>
#include <pcre.h>

int is_match (char *src, char *pattern)
{
    pcre *re;

    const char *error;

    int erroffset;

    int rc;

    re = pcre_compile (pattern,       /* the pattern */
               0,       /* default options */
               &error,       /* for error message */
               &erroffset, /* for error offset */
               NULL);       /* use default character tables */

/* Compilation failed: print the error message and exit */
    if (re == NULL)
    {
    printf ("PCRE compilation failed at offset %d: %s\n", erroffset,
        error);
    return -1;
    }

    rc = pcre_exec (re,        /* the compiled pattern */
            NULL, /* no extra data - we didn't study the pattern */
            src, /* the src string */
            strlen (src), /* the length of the src */
            0,        /* start at offset 0 in the src */
            0,        /* default options */
            NULL, 0);

/* If Matching failed: */
    if (rc < 0)
    {
    free (re);
    return -1;
    }

    free (re);
    return rc;
}

int main (int argc, char **argv)
{
    const char *pattern = "^good_a.*$";

    argv[1] = "good_afmbone..se";

    int result = is_match (argv[1], (char *) pattern);

    printf ("result is: %d\n", result);

    return 0;
}


在ubuntu上编译此程序:
gcc -o pcre_demo file_name.c -lpcre

如果编译的时候,提示找不到库文件libpcre.so.0的话,查看一下:/etc/ld.so.conf.d/libc.conf文件,里面是否包含一句:/usr/local/lib,如果没有则添加上吧。
添加上后,使用sudo ldconfig即可,重新编译即可。

运行结果:
result is: 0

posted on 2010-11-13 01:47  startup  阅读(1082)  评论(0编辑  收藏  举报

导航