C로 정규식라이브러리 사용

Language/C 2012. 1. 5. 08:24
     #include <stdio.h>
          #include <regex.h>
          #include <stdlib.h>
          
          void match_print(const char *buf, int start, int end)
          {
                  int i,j;
                  fprintf(stderr,"|");
                  for( i=0;i<end;i++ )
                          if( i >= start )
                                  fprintf(stderr,"%c", buf[i] );
                  fprintf(stderr,"|\n");
          }
          
          int main()
          {
                  int i;
                  int result;
                  int start=0, end=0;
                  char *str = "A WikiWikiWeb is a collaborative hypertext environment, with an emphasis on easy access to and modification of information.";
                  regex_t *compiled;
                  regmatch_t *matchptr;
                  size_t nmatch;
          
                  if( (compiled = (regex_t*)malloc(sizeof(regex_t))) == NULL ) {
                          fprintf(stderr, "regex_t malloc error\n" );
                          exit(-1);
                  }
          
                  if( regcomp( compiled, "[^ ]*t", REG_EXTENDED | REG_ICASE ) != 0 ) {
                          fprintf(stderr, "regcomp error\n" );
                          exit(-1);
                  }
          
                  nmatch = compiled->re_nsub+1;
          
                  if( (matchptr = (regmatch_t*)malloc(sizeof(regmatch_t)*nmatch)) == NULL ) {
                          fprintf(stderr, "regmatch_t malloc error\n" );
                          exit(-1);
                  }
          
                  while( (result = regexec( compiled, str+start, nmatch, matchptr, 0)) == 0 ) {
                          match_print( str, start+matchptr->rm_so, start+matchptr->rm_eo );
                          start += matchptr->rm_eo;
                  }
          
                  regfree( compiled );
          }

'Language > C' 카테고리의 다른 글

포인터, 배열, 구조체 연산  (0) 2012.01.11
html 태그 제거  (0) 2012.01.05
패턴 매칭 ( Pattern Matching )  (0) 2012.01.05
C 정규식  (0) 2012.01.05
access() 파일 존재나 접근 권한을 확인합니다.  (0) 2011.12.29
: