sábado 7 de noviembre de 2009

Expresiones regulares en C.

El siguiente es un ejemplo de como utilizar expresiones regulares (POSIX RegEx) en C.

Para windows, existe una implementación del módulo regex aquí. Con este sería posible compilar la aplicación (yo lo probé y funcionó), basta con agregar los directorios de includes y librerías, y decirle al compilador que enlace con la librería de regex.

 1 /* Ejemplo simple de expresiones regulares en C.
 2  * Para compilar:
 3  * linux:   $ gcc ejemplo_regex.c -o ejemplo_regex -D_GNU_SOURCE -D__LINUX__
 4  * macosx:  $ gcc ejemplo_regex.c -o ejemplo_regex -D__BSD__
 6 */
 7 //#define _GNU_SOURCE
 8 #include <stdio.h>
 9 #include <stdlib.h>
10 #include <string.h>
11
12 #ifndef _POSIX_C_SOURCE
13 # define _POSIX_C_SOURCE
14 #endif
15 #include <regex.h>
16
17 #ifndef __LINUX__
18 char * strndup (char * from, int len)
19 {
20     char * ret_str = NULL;
21     
22     ret_str= (char *)malloc ((len+1)*sizeof(char));
23     if (ret_str)
24     {
25         strncpy (ret_str,from, len);
26         ret_str[len]='\0';
27     }
28     return ret_str;
29 }
30 #endif
31
32 char * get_string (char * str, regmatch_t m)
33 {
34     char * dup = NULL;
35     int from = m.rm_so;
36     int to   = m.rm_eo;
37
38     if (from != -1)
39     {
40         dup = strndup(str+from, (size_t)to-from);
41     }
42     return dup;
43 }
44
45 main ()
46 {
47     regex_t regex;
48     regmatch_t m[4];
49     int i=0;
50     char * pattern ="(^[^\t]+)(\t)([^\t]+$)";  
51     char * target = "hola\tchau";
52
53     char * temp;
54
55     regcomp (&regex, pattern, REG_EXTENDED);
56     regexec (&regex, target, 4, m, 0);
57     regfree (&regex);
58     for (i=0; i<4; i++)
59     {
60         temp = get_string (target, m[i]);
61         if (temp)
62         {
63             printf ("match: --%s--\n", temp);
64             free (temp);
65         }
66     }
67 }

0 comentarios:

Publicar un comentario en la entrada

Suscribirse a Enviar comentarios [Atom]

<< Página principal