chiark / gitweb /
Monoalphabetic match filter.
[anag] / regexp.c
1 /* -*-c-*-
2  *
3  * $Id: regexp.c,v 1.1 2002/08/11 12:58:09 mdw Exp $
4  *
5  * Matches regular expressions
6  *
7  * (c) 2002 Mark Wooding
8  */
9
10 /*----- Licensing notice --------------------------------------------------* 
11  *
12  * This file is part of Anag: a simple wordgame helper.
13  *
14  * Anag is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  * 
19  * Anag is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  * 
24  * You should have received a copy of the GNU General Public License
25  * along with Anag; if not, write to the Free Software Foundation,
26  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27  */
28
29 /*----- Revision history --------------------------------------------------* 
30  *
31  * $Log: regexp.c,v $
32  * Revision 1.1  2002/08/11 12:58:09  mdw
33  * Added support for regular expression matching, if supported by the C
34  * library.
35  *
36  * Revision 1.1  2001/02/04 17:14:42  mdw
37  * Initial checkin
38  *
39  */
40
41 /*----- Header files ------------------------------------------------------*/
42
43 #ifdef HAVE_CONFIG_H
44 #  include "config.h"
45 #endif
46
47 #ifndef HAVE_REGCOMP
48   extern int dummy;
49 #else
50
51 #include "anag.h"
52 #include <regex.h>
53
54 /*----- Data structures ---------------------------------------------------*/
55
56 typedef struct node_regexp {
57   node n;
58   const char *s;
59   regex_t rx;
60 } node_regexp;
61
62 /*----- Main code ---------------------------------------------------------*/
63
64 /* --- Node matcher --- */
65
66 static int n_regexp(node *nn, const char *p, size_t sz)
67 {
68   node_regexp *n = (node_regexp *)nn;
69   int e;
70
71   switch (e = regexec(&n->rx, p, 0, 0, 0)) {
72     case 0:
73       return 1;
74     case REG_NOMATCH:
75       return 0;
76     default: {
77       char buf[256];
78       regerror(e, &n->rx, buf, sizeof(buf));
79       die("error matching regexp `%s' against `%s': %s",
80           n->s, p, buf);
81     } break;
82   }
83   return (0);
84 }
85
86 /* --- Node creation --- */
87
88 node *regexp(const char *const *av)
89 {
90   node_regexp *n = xmalloc(sizeof(*n));
91   int e;
92   n->n.func = n_regexp;
93   if ((e = regcomp(&n->rx, av[0],
94                    REG_EXTENDED | REG_ICASE | REG_NOSUB)) != 0) {
95     char buf[256];
96     regerror(e, &n->rx, buf, sizeof(buf));
97     die("bad regular expression `%s': %s", av[0], buf);
98   }
99   return (&n->n);
100 }
101
102 /*----- That's all, folks -------------------------------------------------*/
103
104 #endif