| 1 | #include <string.h> |
|---|
| 2 | #include "owl.h" |
|---|
| 3 | |
|---|
| 4 | void owl_regex_init(owl_regex *re) |
|---|
| 5 | { |
|---|
| 6 | re->negate=0; |
|---|
| 7 | re->string=NULL; |
|---|
| 8 | } |
|---|
| 9 | |
|---|
| 10 | int owl_regex_create(owl_regex *re, const char *string) |
|---|
| 11 | { |
|---|
| 12 | int ret; |
|---|
| 13 | char buff1[LINE]; |
|---|
| 14 | const char *ptr; |
|---|
| 15 | |
|---|
| 16 | re->string=owl_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 | regerror(ret, NULL, buff1, LINE); |
|---|
| 29 | owl_function_makemsg("Error in regular expression: %s", buff1); |
|---|
| 30 | owl_free(re->string); |
|---|
| 31 | re->string=NULL; |
|---|
| 32 | return(-1); |
|---|
| 33 | } |
|---|
| 34 | |
|---|
| 35 | return(0); |
|---|
| 36 | } |
|---|
| 37 | |
|---|
| 38 | int owl_regex_create_quoted(owl_regex *re, const char *string) |
|---|
| 39 | { |
|---|
| 40 | char *quoted; |
|---|
| 41 | |
|---|
| 42 | quoted=owl_text_quote(string, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH); |
|---|
| 43 | owl_regex_create(re, quoted); |
|---|
| 44 | owl_free(quoted); |
|---|
| 45 | return(0); |
|---|
| 46 | } |
|---|
| 47 | |
|---|
| 48 | int owl_regex_compare(owl_regex *re, const char *string, int *start, int *end) |
|---|
| 49 | { |
|---|
| 50 | int out, ret; |
|---|
| 51 | regmatch_t match; |
|---|
| 52 | |
|---|
| 53 | /* if the regex is not set we match */ |
|---|
| 54 | if (!owl_regex_is_set(re)) { |
|---|
| 55 | return(0); |
|---|
| 56 | } |
|---|
| 57 | |
|---|
| 58 | ret=regexec(&(re->re), string, 1, &match, 0); |
|---|
| 59 | out=ret; |
|---|
| 60 | if (re->negate) { |
|---|
| 61 | out=!out; |
|---|
| 62 | match.rm_so = 0; |
|---|
| 63 | match.rm_eo = strlen(string); |
|---|
| 64 | } |
|---|
| 65 | if (start != NULL) *start = match.rm_so; |
|---|
| 66 | if (end != NULL) *end = match.rm_eo; |
|---|
| 67 | return(out); |
|---|
| 68 | } |
|---|
| 69 | |
|---|
| 70 | int owl_regex_is_set(owl_regex *re) |
|---|
| 71 | { |
|---|
| 72 | if (re->string) return(1); |
|---|
| 73 | return(0); |
|---|
| 74 | } |
|---|
| 75 | |
|---|
| 76 | const char *owl_regex_get_string(owl_regex *re) |
|---|
| 77 | { |
|---|
| 78 | return(re->string); |
|---|
| 79 | } |
|---|
| 80 | |
|---|
| 81 | void owl_regex_copy(owl_regex *a, owl_regex *b) |
|---|
| 82 | { |
|---|
| 83 | owl_regex_create(b, a->string); |
|---|
| 84 | } |
|---|
| 85 | |
|---|
| 86 | void owl_regex_free(owl_regex *re) |
|---|
| 87 | { |
|---|
| 88 | if (re->string) { |
|---|
| 89 | owl_free(re->string); |
|---|
| 90 | regfree(&(re->re)); |
|---|
| 91 | } |
|---|
| 92 | } |
|---|