Skip to content

Commit

Permalink
Fix and test rz_regex_full_match_str
Browse files Browse the repository at this point in the history
  • Loading branch information
Rot127 committed Feb 1, 2024
1 parent e818180 commit 7c820a9
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
6 changes: 4 additions & 2 deletions librz/util/regex.c
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@ RZ_API RZ_OWN RzStrBuf *rz_regex_full_match_str(const char *pattern, const char
goto fini;
}

size_t i = 1;
void **m;
rz_pvector_foreach (matches, m) {
RzPVector *match_groups = *m;
Expand All @@ -341,11 +342,12 @@ RZ_API RZ_OWN RzStrBuf *rz_regex_full_match_str(const char *pattern, const char
goto fini;
}
// No separator in case of only one match
if (rz_pvector_len(matches) == 1 && !rz_strbuf_appendf(sbuf, "%-.*s", (int)match->len, t)) {
goto fini;
if (i == rz_pvector_len(matches)) {
rz_strbuf_appendf(sbuf, "%-.*s", (int)match->len, t);
} else if (!rz_strbuf_appendf(sbuf, "%-.*s%s", (int)match->len, t, separator)) {
goto fini;
}
++i;
}

fini:
Expand Down
23 changes: 23 additions & 0 deletions test/unit/test_regex.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

#include <rz_regex.h>
#include "minunit.h"
#include <rz_util/rz_strbuf.h>
#include <rz_util/rz_str.h>
#include <rz_vector.h>

Expand Down Expand Up @@ -41,6 +42,27 @@ bool test_rz_regex_extend_space(void) {
mu_end;
}

bool test_rz_regex_all_to_str(void) {
RzRegex *reg = rz_regex_new("123", RZ_REGEX_EXTENDED, 0);
mu_assert_notnull(reg, "Regex was NULL");
RzStrBuf *res = rz_regex_full_match_str("(123)", "123 123 123", RZ_REGEX_ZERO_TERMINATED, RZ_REGEX_DEFAULT, RZ_REGEX_DEFAULT, "\n");
char *str = rz_strbuf_drain(res);
mu_assert_streq(str, "123\n123\n123", "String match failed.");
free(str);

res = rz_regex_full_match_str("(123)", "123", RZ_REGEX_ZERO_TERMINATED, RZ_REGEX_DEFAULT, RZ_REGEX_DEFAULT, "\n");
str = rz_strbuf_drain(res);
mu_assert_streq(str, "123", "String match failed.");
free(str);

res = rz_regex_full_match_str("(123)", "", RZ_REGEX_ZERO_TERMINATED, RZ_REGEX_DEFAULT, RZ_REGEX_DEFAULT, "\n");
str = rz_strbuf_drain(res);
mu_assert_streq(str, "", "String match failed.");
free(str);
rz_regex_free(reg);
mu_end;
}

bool test_rz_reg_exec(void) {
const char *p = "abc|123";
RzRegex *reg = rz_regex_new(p, RZ_REGEX_EXTENDED, 0);
Expand Down Expand Up @@ -122,4 +144,5 @@ int main() {
mu_run_test(test_rz_regex_extend_space);
mu_run_test(test_rz_reg_exec);
mu_run_test(test_rz_regex_capture);
mu_run_test(test_rz_regex_all_to_str);
}

0 comments on commit 7c820a9

Please sign in to comment.