1 /* regex_feature.c -- helper functions for recognizers using regexes
2 
3    Copyright (C) 2000 Carl Worth
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, or (at your option)
8    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 
16 #include <sys/types.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <regex.h>
20 
21 #include "regex_feature.h"
22 #include "sprintf_alloc.h"
23 
24 #ifdef DMALLOC
25 #include "dmalloc.h"
26 #endif
27 
regex_feature_alloc(char * regex_str)28 regex_t *regex_feature_alloc(char *regex_str)
29 {
30 #define RE_ERR_MSG_LEN 255
31     char err_msg[RE_ERR_MSG_LEN];
32     char *regex_str_complete;
33     regex_t *regex;
34     int err;
35 
36     regex = malloc(sizeof(regex_t));
37     if (regex == NULL) {
38 	fprintf(stderr, "%s: Out of memory.\n", __FUNCTION__);
39 	return NULL;
40     }
41 
42     sprintf_alloc(&regex_str_complete, "^%s$", regex_str);
43     err = regcomp(regex, regex_str_complete, REG_EXTENDED | REG_NOSUB);
44     free(regex_str_complete);
45     if (err) {
46 	regerror(err, regex, err_msg, RE_ERR_MSG_LEN);
47 	fprintf(stderr, "%s: An error occurred during regcomp(%s): %s\n",
48 		__FUNCTION__, regex_str_complete, err_msg);
49 	return NULL;
50     }
51 
52     return regex;
53 }
54 
regex_feature_free(regex_t * regex)55 void regex_feature_free(regex_t *regex)
56 {
57     regfree(regex);
58     free(regex);
59 }
60 
regex_feature_recognize(regex_t * regex,char * sequence)61 double regex_feature_recognize(regex_t *regex, char *sequence)
62 {
63     int res;
64 
65     res = regexec(regex, sequence, 0, 0, 0);
66 
67     if (res == REG_NOMATCH)
68 	return 0.0;
69     else
70 	return 1.0;
71 }
72