First parts of index_rules system (ICU support).
[idzebra-moved-to-github.git] / util / rob_regexp.c
1 /* $Id: rob_regexp.c,v 1.1 2007-10-23 12:26:26 adam Exp $
2    Copyright (C) 1995-2007
3    Index Data ApS
4
5    This file is part of the Zebra server.
6
7    Zebra is free software; you can redistribute it and/or modify it under
8    the terms of the GNU General Public License as published by the Free
9    Software Foundation; either version 2, or (at your option) any later
10    version.
11
12    Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13    WARRANTY; without even the implied warranty of MERCHANTABILITY or
14    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15    for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with Zebra; see the file LICENSE.zebra.  If not, write to the
19    Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20    02111-1307, USA.
21 */
22
23 /** 
24     \brief Rob Pike's regular expresion parser
25     
26     Taken verbatim from Beautiful code.. ANSIfied a bit.
27  */
28   
29
30 #include <assert.h>
31 #include <stdlib.h>
32 #include <ctype.h>
33 #include <string.h>
34
35 #include "rob_regexp.h"
36 #include <yaz/xmalloc.h>
37 #include <yaz/wrbuf.h>
38 #include <yaz/log.h>
39
40 static int matchhere(const char *regexp, const char *text);
41 static int matchstar(int c, const char *regexp, const char *text);
42
43 int zebra_rob_regexp(const char *regexp, const char *text)
44 {
45     if (regexp[0] == '^')
46         return matchhere(regexp+1, text);
47     do 
48     {
49         if (matchhere(regexp, text))
50             return 1;
51     }
52     while (*text++);
53     return 0;
54 }
55
56 static int matchhere(const char *regexp, const char *text)
57 {
58     if (regexp[0] == '\0')
59         return 1;
60     if (regexp[1] == '*')
61         return matchstar(regexp[0], regexp+2, text);
62     if (regexp[0] == '$' && regexp[1] == '\0')
63         return *text == '\0';
64     if (*text && (regexp[0] == '.' || regexp[0] == *text))
65         return matchhere(regexp+1, text+1);
66     return 0;
67 }
68
69 static int matchstar(int c, const char *regexp, const char *text)
70 {
71     do
72     {
73         if (matchhere(regexp, text))
74             return 1;
75     }
76     while (*text && (*text++ == c || c == '.'));
77     return 0;
78 }
79
80
81 /*
82  * Local variables:
83  * c-basic-offset: 4
84  * indent-tabs-mode: nil
85  * End:
86  * vim: shiftwidth=4 tabstop=8 expandtab
87  */
88