1 /*
2 Anacron - run commands periodically
3 Copyright (C) 1998 Itai Tzur <itzur@actcom.co.il>
4 Copyright (C) 1999 Sean 'Shaleh' Perry <shaleh@debian.org>
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 The GNU General Public License can also be found in the file
21 `COPYING' that comes with the Anacron source distribution.
22 */
23
24
25 #include <stdio.h>
26 #include <regex.h>
27 #include <stdarg.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include "matchrx.h"
31
32 int
33 match_rx(const char *rx, char *string, unsigned int n_sub, /* char **substrings */...)
/* ![[previous]](../icons/n_left.png)
![[next]](../icons/n_right.png)
![[first]](../icons/n_first.png)
![[last]](../icons/n_last.png)
![[top]](../icons/top.png)
![[bottom]](../icons/bottom.png)
![[index]](../icons/index.png)
*/
34 /* Return 1 if the regular expression "*rx" matches the string "*string",
35 * 0 if not, -1 on error.
36 * "Extended" regular expressions are used.
37 * Additionally, there should be "n_sub" "substrings" arguments. These,
38 * if not NULL, and if the match succeeds are set to point to the
39 * corresponding substrings of the regexp.
40 * The original string is changed, and the substrings must not overlap,
41 * or even be directly adjacent.
42 * This is not the most efficient, or elegant way of doing this.
43 */
44 {
45 int r, n;
46 regex_t crx;
47 va_list va;
48 char **substring;
49 regmatch_t *sub_offsets;
50 sub_offsets = malloc(sizeof(regmatch_t) * (n_sub + 1));
51 if (sub_offsets == NULL)
52 return -1;
53 memset(sub_offsets, 0, sizeof(regmatch_t) * (n_sub + 1));
54
55 if (regcomp(&crx, rx, REG_EXTENDED)) {
56 free(sub_offsets);
57 return -1;
58 }
59 r = regexec(&crx, string, n_sub + 1, sub_offsets, 0);
60 if (r != 0 && r != REG_NOMATCH) {
61 free(sub_offsets);
62 return -1;
63 }
64 regfree(&crx);
65 if (r == REG_NOMATCH) {
66 free(sub_offsets);
67 return 0;
68 }
69
70 va_start(va, n_sub);
71 n = 1;
72 while (n <= n_sub)
73 {
74 substring = va_arg(va, char**);
75 if (substring != NULL)
76 {
77 if (sub_offsets[n].rm_so == -1) {
78 va_end(va);
79 free(sub_offsets);
80 return - 1;
81 }
82 *substring = string + sub_offsets[n].rm_so;
83 *(string + sub_offsets[n].rm_eo) = 0;
84 }
85 n++;
86 }
87 va_end(va);
88 free(sub_offsets);
89 return 1;
90 }