summaryrefslogtreecommitdiff
path: root/xs_regex.h
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--xs_regex.h49
1 files changed, 49 insertions, 0 deletions
diff --git a/xs_regex.h b/xs_regex.h
index b86949e..6fb6cca 100644
--- a/xs_regex.h
+++ b/xs_regex.h
@@ -8,6 +8,8 @@ xs_list *xs_regex_split_n(const char *str, const char *rx, int count);
8#define xs_regex_split(str, rx) xs_regex_split_n(str, rx, XS_ALL) 8#define xs_regex_split(str, rx) xs_regex_split_n(str, rx, XS_ALL)
9xs_list *xs_regex_match_n(const char *str, const char *rx, int count); 9xs_list *xs_regex_match_n(const char *str, const char *rx, int count);
10#define xs_regex_match(str, rx) xs_regex_match_n(str, rx, XS_ALL) 10#define xs_regex_match(str, rx) xs_regex_match_n(str, rx, XS_ALL)
11xs_list *xs_regex_replace_n(const char *str, const char *rx, const char *rep, int count);
12#define xs_regex_replace(str, rx, rep) xs_regex_replace_n(str, rx, rep, XS_ALL)
11 13
12#ifdef XS_IMPLEMENTATION 14#ifdef XS_IMPLEMENTATION
13 15
@@ -75,6 +77,53 @@ xs_list *xs_regex_match_n(const char *str, const char *rx, int count)
75 return list; 77 return list;
76} 78}
77 79
80
81xs_list *xs_regex_replace_n(const char *str, const char *rx, const char *rep, int count)
82/* replaces all matches with the rep string. If it contains unescaped &,
83 they are replaced with the match */
84{
85 xs_str *s = xs_str_new(NULL);
86 xs *split = xs_regex_split_n(str, rx, count);
87 xs_list *p;
88 xs_val *v;
89 int n = 0;
90 int pholder = !!strchr(rep, '&');
91
92 p = split;
93 while (xs_list_iter(&p, &v)) {
94 if (n & 0x1) {
95 if (pholder) {
96 /* rep has a placeholder; process char by char */
97 const char *p = rep;
98
99 while (*p) {
100 if (*p == '&')
101 s = xs_str_cat(s, v);
102 else {
103 if (*p == '\\')
104 p++;
105
106 if (!*p)
107 break;
108
109 s = xs_append_m(s, p, 1);
110 }
111
112 p++;
113 }
114 }
115 else
116 s = xs_str_cat(s, rep);
117 }
118 else
119 s = xs_str_cat(s, v);
120
121 n++;
122 }
123
124 return s;
125}
126
78#endif /* XS_IMPLEMENTATION */ 127#endif /* XS_IMPLEMENTATION */
79 128
80#endif /* XS_REGEX_H */ 129#endif /* XS_REGEX_H */