/* * regex_test.c - testa tinyblocks-regex (POSIX ERE). */ #include #include #include #include #include static int fails = 0; #define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0) int main(void) { CHECK(tb_regex_test("abc123def", "[0-9]+"), "test encontra digitos"); CHECK(!tb_regex_test("abcdef", "[0-9]+"), "test rejeita sem digitos"); CHECK(tb_regex_match("aaa", "^a+$"), "match ancorado ok"); CHECK(!tb_regex_match("aaab", "^a+$"), "match ancorado rejeita"); char* s = tb_regex_find("abc123def456", "[0-9]+"); CHECK(s && !strcmp(s, "123"), "find primeiro casamento"); free(s); CHECK(tb_regex_count("abc123def456", "[0-9]+") == 2, "count = 2"); s = tb_regex_group("user@host.com", "([a-z]+)@([a-z.]+)", 1); CHECK(s && !strcmp(s, "user"), "group 1"); free(s); s = tb_regex_group("user@host.com", "([a-z]+)@([a-z.]+)", 2); CHECK(s && !strcmp(s, "host.com"), "group 2"); free(s); CHECK(tb_regex_group_count("", "([a-z]+)@([a-z.]+)") == 2, "group_count = 2"); s = tb_regex_replace("abc123def456", "[0-9]+", "#"); CHECK(s && !strcmp(s, "abc#def#"), "replace todas"); free(s); s = tb_regex_replace("2024-06-15", "([0-9]{4})-([0-9]{2})-([0-9]{2})", "$3/$2/$1"); CHECK(s && !strcmp(s, "15/06/2024"), "replace com backrefs $1..$3"); free(s); s = tb_regex_replace("a.b", "\\.", "$$"); CHECK(s && !strcmp(s, "a$b"), "replace com $$ literal"); free(s); int n = 0; char** parts = tb_regex_split("um,dois,tres", ",", &n); CHECK(parts && n == 3 && !strcmp(parts[0], "um") && !strcmp(parts[1], "dois") && !strcmp(parts[2], "tres"), "split por virgula"); tb_regex_free_list(parts); parts = tb_regex_split("a1b22c", "[0-9]+", &n); CHECK(parts && n == 3 && !strcmp(parts[0], "a") && !strcmp(parts[2], "c"), "split por regex"); tb_regex_free_list(parts); CHECK(!tb_regex_test("x", "[") && strlen(tb_regex_last_error()) > 0, "padrao invalido -> erro"); TinyBlocks* rt; tinyblocks_init(&rt, NULL); TinyBlocks_LibraryBlock* lib = tb_library_register(rt, tb_regex_get_library()); CHECK(tb_rt_find_type(rt, "Regex.Test") && tb_rt_find_type(rt, "Regex.Replace") && tb_rt_find_type(rt, "Regex.Split") && tb_rt_find_type(rt, "Regex.Group"), "blocos Regex.* registrados"); const TinyBlocks_Category* cat = lib ? tb_library_category(lib) : NULL; CHECK(cat && !strcmp(cat->name, "Regex"), "categoria 'Regex'"); tinyblocks_deinit(&rt); if (fails) printf("\n%d FALHA(S)\n", fails); else printf("\nTUDO OK\n"); return fails != 0; }