source: regex.c @ c40d11a

Last change on this file since c40d11a was c40d11a, checked in by David Benjamin <davidben@mit.edu>, 13 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
RevLine 
[7d4fbcd]1#include <string.h>
2#include "owl.h"
3
[e187445]4void owl_regex_init(owl_regex *re)
5{
[7d4fbcd]6  re->negate=0;
7  re->string=NULL;
8}
9
[e19eb97]10int owl_regex_create(owl_regex *re, const char *string)
[e187445]11{
[7d4fbcd]12  int ret;
[c40d11a]13  size_t errbuf_size;
14  char *errbuf;
[e19eb97]15  const char *ptr;
[7d4fbcd]16 
[d4927a7]17  re->string=g_strdup(string);
[7d4fbcd]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) {
[c40d11a]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);
[ddbbcffa]34    g_free(re->string);
[a6560fe]35    re->string=NULL;
[7d4fbcd]36    return(-1);
37  }
38
39  return(0);
40}
41
[e19eb97]42int owl_regex_create_quoted(owl_regex *re, const char *string)
[bc08664]43{
44  char *quoted;
[d427f08]45  int ret;
[bc08664]46 
[d427f08]47  quoted = owl_text_quote(string, OWL_REGEX_QUOTECHARS, OWL_REGEX_QUOTEWITH);
48  ret = owl_regex_create(re, quoted);
[ddbbcffa]49  g_free(quoted);
[d427f08]50  return ret;
[bc08664]51}
52
[89b2daf]53int owl_regex_compare(const owl_regex *re, const char *string, int *start, int *end)
[e187445]54{
[7d4fbcd]55  int out, ret;
[41c9a96]56  regmatch_t match;
[7d4fbcd]57
58  /* if the regex is not set we match */
59  if (!owl_regex_is_set(re)) {
60    return(0);
61  }
62 
[41c9a96]63  ret=regexec(&(re->re), string, 1, &match, 0);
[7d4fbcd]64  out=ret;
65  if (re->negate) {
66    out=!out;
[41c9a96]67    match.rm_so = 0;
68    match.rm_eo = strlen(string);
[7d4fbcd]69  }
[41c9a96]70  if (start != NULL) *start = match.rm_so;
71  if (end != NULL) *end = match.rm_eo;
[7d4fbcd]72  return(out);
73}
74
[89b2daf]75int owl_regex_is_set(const owl_regex *re)
[e187445]76{
[7d4fbcd]77  if (re->string) return(1);
78  return(0);
79}
80
[89b2daf]81const char *owl_regex_get_string(const owl_regex *re)
[e187445]82{
[7d4fbcd]83  return(re->string);
84}
85
[89b2daf]86void owl_regex_copy(const owl_regex *a, owl_regex *b)
[e187445]87{
[41c9a96]88  owl_regex_create(b, a->string);
[7d4fbcd]89}
90
[5cbc929]91void owl_regex_cleanup(owl_regex *re)
[e187445]92{
[cb769bb]93    if (re->string) {
[ddbbcffa]94        g_free(re->string);
[cb769bb]95        regfree(&(re->re));
96    }
[7d4fbcd]97}
Note: See TracBrowser for help on using the repository browser.