mirror of
https://github.com/cesanta/slre.git
synced 2024-11-17 08:55:30 +00:00
Added slre_replace() in the unit test
This commit is contained in:
parent
f20ed682e2
commit
8cfa4336fc
40
slre.c
40
slre.c
@ -368,6 +368,34 @@ static int static_failed_tests = 0;
|
||||
if (!(expr)) FAIL(#expr, __LINE__); \
|
||||
} while (0)
|
||||
|
||||
/* Regex must have exactly one bracket pair */
|
||||
static char *slre_replace(const char *regex, const char *buf,
|
||||
const char *sub) {
|
||||
char *s = NULL;
|
||||
int n, n1, n2, n3, s_len, len = strlen(buf);
|
||||
struct slre_cap cap = { NULL, 0 };
|
||||
|
||||
do {
|
||||
s_len = s == NULL ? 0 : strlen(s);
|
||||
if ((n = slre_match(regex, buf, len, &cap, NULL)) > 0) {
|
||||
n1 = cap.ptr - buf, n2 = strlen(sub),
|
||||
n3 = &buf[n] - &cap.ptr[cap.len];
|
||||
} else {
|
||||
n1 = len, n2 = 0, n3 = 0;
|
||||
}
|
||||
s = realloc(s, s_len + n1 + n2 + n3 + 1);
|
||||
memcpy(s + s_len, buf, n1);
|
||||
memcpy(s + s_len + n1, sub, n2);
|
||||
memcpy(s + s_len + n1 + n2, cap.ptr + cap.len, n3);
|
||||
s[s_len + n1 + n2 + n3] = '\0';
|
||||
|
||||
buf += n > 0 ? n : len;
|
||||
len -= n > 0 ? n : len;
|
||||
} while (len > 0);
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
const char *msg = "";
|
||||
struct slre_cap caps[10];
|
||||
@ -457,6 +485,18 @@ int main(void) {
|
||||
} else {
|
||||
printf("Error parsing [%s]: [%s]\n", request, error_msg);
|
||||
}
|
||||
|
||||
ASSERT(caps[1].len == 11);
|
||||
ASSERT(memcmp(caps[1].ptr, "/index.html", caps[1].len) == 0);
|
||||
}
|
||||
|
||||
{
|
||||
char *s = slre_replace("({{.+?}})",
|
||||
"Good morning, {{foo}}. How are you, {{bar}}?",
|
||||
"Bob");
|
||||
printf("%s\n", s);
|
||||
ASSERT(strcmp(s, "Good morning, Bob. How are you, Bob?") == 0);
|
||||
free(s);
|
||||
}
|
||||
|
||||
printf("Unit test %s (total test: %d, failed tests: %d)\n",
|
||||
|
Loading…
Reference in New Issue
Block a user