代码之家  ›  专栏  ›  技术社区  ›  Aftershock

您知道C++中基于正则表达式的解析器,可以用来解析流吗?

  •  1
  • Aftershock  · 技术社区  · 14 年前

    我想在运行时指定正则表达式,而不是在编译时。 您知道C/C++正则表达式库吗?它可以解析流,并且可以识别相对复杂的正则表达式,例如?

    2 回复  |  直到 14 年前
        1
  •  5
  •   Artyom    14 年前

    AFAIK boost::regex应该知道如何处理流,并且它支持perl正则表达式

        2
  •  1
  •   dmckee --- ex-moderator kitten    14 年前

    好吧,这里有PCRE。

    用pcre实现的最小grep(请注意,要搜索的表达式在运行时在命令行中提供):

    #include <stdlib.h>
    #include <stdio.h>
    #include <errno.h>
    #include "pcre.h"
    #define OVECCOUNT 30    /* should be a multiple of 3 */
    
    /* only needed if your libc doesn't include it! */
    #include "getline.c" 
    
    int main(int argc, char**argv){
      char *res;
      char *fname;
      const char *error;
      int erroroffset;
      pcre *re=NULL;
    
      /* Grab the search expression from the first command line argument */
      if (--argc) {
        res=(++argv)[0];
        re=pcre_compile(res,0,&error,&erroroffset,NULL);
        if (re==NULL) /* compilation failed, bomb out */ exit(1);
      }
    
      /* All further command line arguments are files to grep in */
      while (--argc) {
        FILE*f=NULL;
        fname=(++argv)[0];
    
        if (f=fopen(fname,"r")) {
          char *line=NULL;
          size_t l=0;
          while (-1 != getline(&line,&l,f)) {
        int ovector[OVECCOUNT];
        if ( pcre_exec(re,NULL,line,l,0,0,ovector,OVECCOUNT) > 0 ) {
          printf("%s",line);
        }
    
        free(line);
        line = NULL; l=0;
          }
    
          fclose(f);
        }
      }
      free(re);
      return 0;
    }
    

    $ ./pcregrep char pcregrep.c
    int main(int argc, char**argv){
      char *res;
      char *fname;
      const char *error;
          char *line=NULL;