1 | #include "owl.h" |
---|
2 | |
---|
3 | void owl_regex_init(owl_regex *re) |
---|
4 | { |
---|
5 | re->negate=0; |
---|
6 | re->string=NULL; |
---|
7 | } |
---|
8 | |
---|
9 | int owl_regex_create(owl_regex *re, const char *string) |
---|
10 | { |
---|
11 | int ret; |
---|
12 | size_t errbuf_size; |
---|
13 | char *errbuf; |
---|
14 | const char *ptr; |
---|
15 | |
---|
16 | re->string=g_strdup(string); |
---|
17 | |
---|
18 | ptr=string; |
---|
19 | re->negate=0; |
---|
20 | if (string[0]=='!') { |
---|
21 | ptr++; |
---|
22 | re->negate=1; |
---|
23 | } |
---|
24 | |
---|
25 | /* set the regex */ |
---|
26 | ret=regcomp(&(re->re), ptr, REG_EXTENDED|REG_ICASE); |
---|
27 | if (ret) { |
---|
28 | errbuf_size = regerror(ret, NULL, NULL, 0); |
---|
29 | errbuf = g_new(char, errbuf_size); |
---|
30 | regerror(ret, NULL, errbuf, errbuf_size); |
---|
31 | owl_function_error("Error in regular expression: %s", errbuf); |
---|
32 | g_free(errbuf); |
---|
33 | g_free(re->string); |
---|
34 | re->string=NULL; |
---|
35 | return(-1); |
---|
36 | } |
---|
37 | |
---|
38 | return(0); |
---|
39 | } |
---|
40 | |
---|
41 | int owl_regex_create_quoted(owl_regex *re, const char *string) |
---|
42 | { |
---|
43 | char *quoted; |
---|
44 | int ret; |
---|
45 | |
---|
46 | quoted = owl_text_quote(string, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH); |
---|
47 | ret = owl_regex_create(re, quoted); |
---|
48 | g_free(quoted); |
---|
49 | return ret; |
---|
50 | } |
---|
51 | |
---|
52 | int owl_regex_compare(const owl_regex *re, const char *string, int *start, int *end) |
---|
53 | { |
---|
54 | int out, ret; |
---|
55 | regmatch_t match; |
---|
56 | |
---|
57 | /* if the regex is not set we match */ |
---|
58 | if (!owl_regex_is_set(re)) { |
---|
59 | return(0); |
---|
60 | } |
---|
61 | |
---|
62 | ret=regexec(&(re->re), string, 1, &match, 0); |
---|
63 | out=ret; |
---|
64 | if (re->negate) { |
---|
65 | out=!out; |
---|
66 | match.rm_so = 0; |
---|
67 | match.rm_eo = strlen(string); |
---|
68 | } |
---|
69 | if (start != NULL) *start = match.rm_so; |
---|
70 | if (end != NULL) *end = match.rm_eo; |
---|
71 | return(out); |
---|
72 | } |
---|
73 | |
---|
74 | int owl_regex_is_set(const owl_regex *re) |
---|
75 | { |
---|
76 | if (re->string) return(1); |
---|
77 | return(0); |
---|
78 | } |
---|
79 | |
---|
80 | const char *owl_regex_get_string(const owl_regex *re) |
---|
81 | { |
---|
82 | return(re->string); |
---|
83 | } |
---|
84 | |
---|
85 | void owl_regex_copy(const owl_regex *a, owl_regex *b) |
---|
86 | { |
---|
87 | owl_regex_create(b, a->string); |
---|
88 | } |
---|
89 | |
---|
90 | void owl_regex_cleanup(owl_regex *re) |
---|
91 | { |
---|
92 | if (re->string) { |
---|
93 | g_free(re->string); |
---|
94 | regfree(&(re->re)); |
---|
95 | } |
---|
96 | } |
---|