a10122de |
1 | /* -*-c-*- |
2 | * |
345f33ea |
3 | * $Id: regexp.c,v 1.2 2004/04/08 01:36:19 mdw Exp $ |
a10122de |
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 | |
a10122de |
29 | /*----- Header files ------------------------------------------------------*/ |
30 | |
31 | #ifdef HAVE_CONFIG_H |
32 | # include "config.h" |
33 | #endif |
34 | |
35 | #ifndef HAVE_REGCOMP |
36 | extern int dummy; |
37 | #else |
38 | |
39 | #include "anag.h" |
40 | #include <regex.h> |
41 | |
42 | /*----- Data structures ---------------------------------------------------*/ |
43 | |
44 | typedef struct node_regexp { |
45 | node n; |
46 | const char *s; |
47 | regex_t rx; |
48 | } node_regexp; |
49 | |
50 | /*----- Main code ---------------------------------------------------------*/ |
51 | |
52 | /* --- Node matcher --- */ |
53 | |
54 | static int n_regexp(node *nn, const char *p, size_t sz) |
55 | { |
56 | node_regexp *n = (node_regexp *)nn; |
57 | int e; |
58 | |
59 | switch (e = regexec(&n->rx, p, 0, 0, 0)) { |
60 | case 0: |
61 | return 1; |
62 | case REG_NOMATCH: |
63 | return 0; |
64 | default: { |
65 | char buf[256]; |
66 | regerror(e, &n->rx, buf, sizeof(buf)); |
67 | die("error matching regexp `%s' against `%s': %s", |
68 | n->s, p, buf); |
69 | } break; |
70 | } |
71 | return (0); |
72 | } |
73 | |
74 | /* --- Node creation --- */ |
75 | |
76 | node *regexp(const char *const *av) |
77 | { |
78 | node_regexp *n = xmalloc(sizeof(*n)); |
79 | int e; |
80 | n->n.func = n_regexp; |
81 | if ((e = regcomp(&n->rx, av[0], |
82 | REG_EXTENDED | REG_ICASE | REG_NOSUB)) != 0) { |
83 | char buf[256]; |
84 | regerror(e, &n->rx, buf, sizeof(buf)); |
85 | die("bad regular expression `%s': %s", av[0], buf); |
86 | } |
87 | return (&n->n); |
88 | } |
89 | |
90 | /*----- That's all, folks -------------------------------------------------*/ |
91 | |
92 | #endif |