2e4ca3cca477e305a13549f497f9fa006c9ef75c
[claws.git] / src / string_match.c
1 /*
2  * Sylpheed -- regexp pattern matching utilities
3  * Copyright (C) 2001 Thomas Link, Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20
21 #include "string_match.h"
22
23
24 int string_match_regexp(char * txt, char * rexp,
25                         int size, regmatch_t matches[],
26                         int cflags, int eflags)
27 {
28         regex_t re;
29         int problem;
30
31         problem = regcomp(&re, rexp, cflags);  
32         if (problem == 0) {
33                 problem = regexec(&re, txt, size, matches, eflags);
34         }
35         regfree(&re);
36         return problem == 0;
37 }
38
39 int string_remove_match(char * txt, char * rexp, int cflags, int eflags)
40 {
41         regmatch_t matches[STRING_MATCH_MR_SIZE];
42         int foundp;
43
44         if (strlen(txt) > 0 && strlen(rexp) > 0) {
45                 foundp = string_match_regexp(txt, rexp, STRING_MATCH_MR_SIZE, 
46                                              matches, cflags, eflags);
47         } else {
48                 return -1;
49         }
50
51         if (foundp && matches[0].rm_so != -1 && matches[0].rm_eo != -1) {
52                 if (matches[0].rm_so == matches[0].rm_eo) {
53                         /* in case the match is an empty string */
54                         return matches[0].rm_so + 1;
55                 } else {
56                         strcpy(txt + matches[0].rm_so, txt + matches[0].rm_eo);
57                         return matches[0].rm_so;
58                 }
59         } else {
60                 return -1;
61         }
62 }
63
64 int string_remove_all_matches(char * txt, char * rexp, int cflags, int eflags)
65 {
66         int pos = 0;
67         int pos0 = pos;
68
69         while (pos0 >= 0 && pos < strlen(txt) && strlen(txt) > 0) {
70                 /* printf("%s %d:%d\n", txt, pos0, pos); */
71                 pos0 = string_remove_match(txt + pos, rexp, cflags, eflags);
72                 if (pos0 >= 0) {
73                         pos = pos + pos0;
74                 }
75         }
76         return pos;
77 }