source: regex.c @ cbc8657

release-1.9
Last change on this file since cbc8657 was cbc8657, checked in by David Benjamin <davidben@mit.edu>, 10 years ago
Don't hardcode regerror buffer size This lets us kill the silly LINE macro. regerror can be called first to get the length, and then the data.
  • Property mode set to 100644
File size: 1.8 KB
Line 
1#include <string.h>
2#include "owl.h"
3
4void owl_regex_init(owl_regex *re)
5{
6  re->negate=0;
7  re->string=NULL;
8}
9
10int owl_regex_create(owl_regex *re, const char *string)
11{
12  int ret;
13  size_t errbuf_size;
14  char *errbuf;
15  const char *ptr;
16 
17  re->string=g_strdup(string);
18
19  ptr=string;
20  re->negate=0;
21  if (string[0]=='!') {
22    ptr++;
23    re->negate=1;
24  }
25
26  /* set the regex */
27  ret=regcomp(&(re->re), ptr, REG_EXTENDED|REG_ICASE);
28  if (ret) {
29    errbuf_size = regerror(ret, NULL, NULL, 0);
30    errbuf = g_new(char, errbuf_size);
31    regerror(ret, NULL, errbuf, errbuf_size);
32    owl_function_error("Error in regular expression: %s", errbuf);
33    g_free(errbuf);
34    g_free(re->string);
35    re->string=NULL;
36    return(-1);
37  }
38
39  return(0);
40}
41
42int owl_regex_create_quoted(owl_regex *re, const char *string)
43{
44  char *quoted;
45  int ret;
46 
47  quoted = owl_text_quote(string, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
48  ret = owl_regex_create(re, quoted);
49  g_free(quoted);
50  return ret;
51}
52
53int owl_regex_compare(const owl_regex *re, const char *string, int *start, int *end)
54{
55  int out, ret;
56  regmatch_t match;
57
58  /* if the regex is not set we match */
59  if (!owl_regex_is_set(re)) {
60    return(0);
61  }
62 
63  ret=regexec(&(re->re), string, 1, &match, 0);
64  out=ret;
65  if (re->negate) {
66    out=!out;
67    match.rm_so = 0;
68    match.rm_eo = strlen(string);
69  }
70  if (start != NULL) *start = match.rm_so;
71  if (end != NULL) *end = match.rm_eo;
72  return(out);
73}
74
75int owl_regex_is_set(const owl_regex *re)
76{
77  if (re->string) return(1);
78  return(0);
79}
80
81const char *owl_regex_get_string(const owl_regex *re)
82{
83  return(re->string);
84}
85
86void owl_regex_copy(const owl_regex *a, owl_regex *b)
87{
88  owl_regex_create(b, a->string);
89}
90
91void owl_regex_cleanup(owl_regex *re)
92{
93    if (re->string) {
94        g_free(re->string);
95        regfree(&(re->re));
96    }
97}
Note: See TracBrowser for help on using the repository browser.