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