zoukankan      html  css  js  c++  java
  • pcrecpp高级使用

    昨天简单介绍了一下pcrecpp的使用,常用的匹配函数包括FullMatch和PartilaMatch等,FullMatch和PartilaMatch对于捕获参数的个数都有限制,最多能传16个捕获参数。而且不能够根据模式中的捕获情况动态设定捕获参数。查看了一个pcrecpp的文档,其中提及DoMatch函数能够做更普适的匹配操作。但是关于DoMatch函数的介绍也仅限于此,google搜索也没找到更多的材料。

    因为要用,只好去看了一下pcrecpp的源码,最后终于搞定了,写一个能够根据传入的模式和匹配串执行动态匹配的程序。编码过程中对DoMatch函数有了一些深入的了解,发现DoMatch函数主要是调用DoMatchImpl函数来实现的,并且实际上FullMatch和PartilaMatch等匹配函数也大多是调用DoMatchImpl来实现的,这是一个私有函数,无法直接使用。

    下面还是介绍一下DoMatch函数的使用吧。函数的原型为:

    bool precpp::RE:DoMatch( const StringPiece &  text,Anchor  anchor,int *  consumed,const Arg *const *  args,int  n);

     各个参数的含义如下:

    1. const StringPiece &  text : StringPiece 是pcrecpp中定义的类型,暂时理解为一个字符串就行了

    2.Anchor  anchor:是锚点的意思,UNANCHORED,ANCHOR_START,ANCHOR_BOTH。具体含义自己理解吧,pcrecpp的实现中FullMatch设置的选项是ANCHOR_BOTH,PartilaMatch设置的是AUNANCHORED。

    3.int *  consumed:匹配消耗目标串中的字符数

    4.const Arg *const *  args:这个参数的类型可以作为考察对const定义理解的考题,呵呵。我的理解是一个args是一个指针,这个指向一个常量,该常量又是一个指向常量Arg类型的指针。其实函数需要的就是一个数组,数组中的元素是指向常量Arg类型的常量指针。

    5.int  n:这是需要捕获的子串的个数,与args数组的大小相等。

    好了,下面介绍一下我的小程序吧。

    #define PCRE_STATIC // 静态库编译选项
    #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 <title>Hello World</title> 222";   // 要被用来匹配的字符串
        char  pattern [] = "<title>(.*)</(tit)le>";              // 将要被编译的字符串形式的正则表达式
        printf("String : %s/n", src);
        printf("Pattern: /"%s/"/n", pattern);
        re = pcre_compile(pattern,       // pattern, 输入参数,将要被编译的字符串形式的正则表达式
                          0,            // options, 输入参数,用来指定编译时的一些选项
                          &error,       // errptr, 输出参数,用来输出错误信息
                          &erroffset,   // erroffset, 输出参数,pattern中出错位置的偏移量
                          NULL);        // tableptr, 输入参数,用来指定字符表,一般情况用NULL
        // 返回值:被编译好的正则表达式的pcre内部表示结构
        if (re == NULL) {                 //如果编译失败,返回错误信息
            printf("PCRE compilation failed at offset %d: %s/n", erroffset, error);
            return 1;
        }
        rc = pcre_exec(re,            // code, 输入参数,用pcre_compile编译好的正则表达结构的指针
                       NULL,          // extra, 输入参数,用来向pcre_exec传一些额外的数据信息的结构的指针
                       src,           // subject, 输入参数,要被用来匹配的字符串
                       strlen(src),  // length, 输入参数, 要被用来匹配的字符串的指针
                       0,             // startoffset, 输入参数,用来指定subject从什么位置开始被匹配的偏移量
                       0,             // options, 输入参数, 用来指定匹配过程中的一些选项
                       ovector,       // ovector, 输出参数,用来返回匹配位置偏移量的数组
                       OVECCOUNT);    // ovecsize, 输入参数, 用来返回匹配位置偏移量的数组的最大大小
        // 返回值:匹配成功返回非负数,没有匹配返回负数
        if (rc < 0) {                     //如果没有匹配,返回错误信息
            if (rc == PCRE_ERROR_NOMATCH) printf("Sorry, no match .../n");
            else printf("Matching error %d/n", rc);
            pcre_free(re);
            return 1;
        }
        printf("/nOK, has matched .../n/n");   //没有出错,已经匹配
        for (i = 0; i < rc; i++) {             //分别取出捕获分组 $0整个正则公式 $1第一个()
            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);
        }
        pcre_free(re);                     // 编译正则表达式re 释放内存
        return 0;
    }


    
    C++的
    

     #include<iostream>
     #include<string>
     #include<string.h>
     #include<pcrecpp.h>
     #include<vector>
     using namespace std;
     
     //计算string中的匹配括号数,如果括号未完全匹配,则返回-1,否则返回括号对数
     int countParenthesis(string pt);
    
    
     //返回0表示匹配成功 其它表示失败
     //匹配的结果以string的形式依次存储在matched中
     int  match(string pattern,string subject,bool isFullMatch,vector<string> &matched)
     {
         pcrecpp::RE_Options opt;
         opt.set_caseless(true); 
         try{
             pcrecpp::RE re = pcrecpp::RE(pattern,opt);
     
             int num = countParenthesis(pattern);//根据模式中的括号数目来决定捕获字符串的个数
             if(num>0){
                 string *ss = new string[num];
                 const pcrecpp::Arg **args = new const pcrecpp::Arg*[num];  //定义args,注意它的类型哦
     
                 for(int i=0;i<num;i++){
                     args[i] = new pcrecpp::Arg(&ss[i]); //需要使用pcrecpp::Arg的构造函数
                 }
     
                 int consumed = 0;
                 if(isFullMatch){
                     re.DoMatch(subject,pcrecpp::RE::ANCHOR_BOTH,&consumed,args,num);
                 }else{
                     re.DoMatch(subject,pcrecpp::RE::UNANCHORED,&consumed,args,num);
                 }
     
                 int ret = -1;
                 if( re.NumberOfCapturingGroups() > 0){
                     matched.clear();
                     for(int i=0;i<num;i++){
                         matched.push_back(ss[i]);
                     }
                     ret = 0;//匹配成功,返回值设为0
                 }
     
                 for(int i=0;i<num;i++){
                     delete args[i] ;
                 }
                 delete[] ss;
                 delete[] args;
     
                 return ret;
     
             }else if(num==0){
                 if(isFullMatch){
                     bool res = re.FullMatch(subject);
                     return res==true ? 0 : -1;
                 }else{
                     bool res  = re.PartialMatch(subject);
                     return res==true ? 0 : -1;
                 }
             }else{
                 cout<<"the Parenthesis is not paired!"<<endl;
                 return -1;
             }
         }catch(exception ex){
             cout<<"some exception happened! please check you pattern";
    
             return -1;
         }
     }
     
     int main()
     {
         string content("<<<中国><E><B>><C>A>");
         pcrecpp::RE_Options  options;
         options.set_caseless(true);//不区分大小写
         string pattern = ("(<(<<中国><E><B>>)?<(<F><G>)?C>A>)");
     
       //可以更改传入的目标串和模式动态决定捕获多少个子串,都以string存起来
         vector<string> matched;
         match(pattern,content,true,matched);
         cout<<matched.size()<<endl;
         for(vector<string>::iterator itr = matched.begin(); itr!=matched.end(); itr++)
             cout<<*itr<<endl
    
         return 0;
    

    还是C比较简洁,看着舒服,C++以后要优化下

    弄了半天这个东西,希望对大家有帮助。

  • 相关阅读:
    冲刺周期会议三
    冲刺周期会议二
    冲刺周期会议一
    日常会议
    总结会议及站立会议(六)
    站立会议(五)
    站立会议(四)
    【自习任我行】
    软件小创意
    团队项目题目拟定
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9410112.html
Copyright © 2011-2022 走看看