summaryrefslogtreecommitdiff
path: root/xs_regex.h
diff options
context:
space:
mode:
Diffstat (limited to 'xs_regex.h')
-rw-r--r--xs_regex.h47
1 files changed, 47 insertions, 0 deletions
diff --git a/xs_regex.h b/xs_regex.h
new file mode 100644
index 0000000..75ccfc3
--- /dev/null
+++ b/xs_regex.h
@@ -0,0 +1,47 @@
1/* copyright (c) 2022 grunfink - MIT license */
2
3#ifndef _XS_REGEX_H
4
5#define _XS_REGEX_H
6
7d_char *xs_regex_match(char *str, char *rx, int count);
8#define xs_regex_matchall(str, rx) xs_regex_match(str, rx, 0xfffffff)
9
10#ifdef XS_IMPLEMENTATION
11
12#include <regex.h>
13
14d_char *xs_regex_match(char *str, char *rx, int count)
15/* returns a list with upto count matches */
16{
17 regex_t re;
18 regmatch_t rm;
19 d_char *list = NULL;
20 int offset = 0;
21 char *p;
22
23 if (regcomp(&re, rx, REG_EXTENDED))
24 return NULL;
25
26 list = xs_list_new();
27
28 while (count > 0 && !regexec(&re, (p = str + offset), 1, &rm, offset > 0 ? REG_NOTBOL : 0)) {
29 /* add the first part */
30 list = xs_list_append_m(list, p + rm.rm_so, rm.rm_eo - rm.rm_so);
31
32 /* add the asciiz */
33 list = xs_str_cat(list, "");
34
35 offset += rm.rm_eo;
36
37 count--;
38 }
39
40 regfree(&re);
41
42 return list;
43}
44
45#endif /* XS_IMPLEMENTATION */
46
47#endif /* XS_REGEX_H */