关于PCRE在VC中的使用

来源:互联网 发布:徐海乔 知乎 编辑:程序博客网 时间:2024/06/01 15:36

PCRE 官网 http://www.pcre.org/
PCRE Windows版本(包含已编译文件) http://www.psyon.org/projects/pcre-win32/index.php

1)psyon.org编译好的lib只能在vc7以上版本使用,因为这些lib使用了/GS编译开关。
在vc显示如下错误:
error LNK2001:unresolved external symbol __security_cookie
2)用静态链接一定要预定义PCRE_STATIC宏。
3)自己编译PCRE的注意事项(未尝试)
运行时库与宿主程序一致;
默认pcre以递归方式调用match处理较大的串时可能栈溢出,
处理方法一:config.h中#define NO_RECURSE
方法二:采用pcre_recurse_malloc从堆中分配内存。


//---------------------------
PCRE测试代码
/* Compile thuswise:   
*   gcc -Wall pcre1.c -I/usr/local/include -L/usr/local/lib -R/usr/local/lib -lpcre
*     
*/    

#include <stdio.h>
#include <string.h>
#include <pcre.h>
               
#define OVECCOUNT 30    /* should be a multiple of 3 */
       
int main()
{              
        pcre            *re;
        const char      *error;
        int             erroffset;
        int             ovector[OVECCOUNT];
        int             rc, i;
       
        char            src    [] = "111 <title>Hello World</title> 222";
        char            pattern   [] = "<title>(.*)</title>";
               
        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;
}