[WikiDyd] [TitleIndex] [WordIndex

Wyrażenia regularne

JiMP2

Autorzy: Stephen Kleene i Ken Thompson.

W języku C:

   1 #include <stdio.h>
   2 #include <regex.h>
   3 #include <string.h>
   4 
   5 int
   6 main(int argc, char **argv)
   7 {
   8     char            buff[1024];
   9     char            uidaAsString[64];
  10     char            login[64];
  11     regex_t         preg;
  12     int             comp = regcomp(&preg, "^([^:]+):[^:]+:([^:]+):.*$", REG_EXTENDED);
  13     regmatch_t      pmatch[3];  /* we need two matches: the entire regex
  14                                  * and one paranthesized subexpr. */
  15     FILE*           in;
  16     char*           fin = argc > 1 ? argv[1] : "/etc/passwd";
  17 
  18     if( (in= fopen(fin,"r")) == NULL ) {
  19       fprintf( stderr, "%s: can't read input (file %s) - exiting.\n", argv[0], fin );
  20       return 1;
  21     }
  22 
  23     while (fgets(buff, 1024, in) != NULL) {
  24         if (regexec(&preg, buff, 3, pmatch, 0) == 0) {
  25             strncpy(login, buff + pmatch[1].rm_so, pmatch[1].rm_eo - pmatch[1].rm_so);
  26             login[pmatch[1].rm_eo - pmatch[1].rm_so] = '\0';
  27             strncpy(uidaAsString, buff + pmatch[2].rm_so, pmatch[2].rm_eo - pmatch[2].rm_so);
  28             uidaAsString[pmatch[2].rm_eo - pmatch[2].rm_so] = '\0';
  29             printf( "uid: %s, login: %s\n", uidaAsString, login );
  30         }
  31     }
  32     fclose(in);
  33     return 0;
  34 }

2015-09-23 06:44