From 6d0f04375df942985292d0a6b6e487db9a09f3fa Mon Sep 17 00:00:00 2001 From: Bruce Hill Date: Mon, 16 Sep 2024 15:12:54 -0400 Subject: Have Text:matches() return an optional array of matches --- stdlib/patterns.c | 16 +++++++++++++--- stdlib/patterns.h | 2 +- 2 files changed, 14 insertions(+), 4 deletions(-) (limited to 'stdlib') diff --git a/stdlib/patterns.c b/stdlib/patterns.c index 0df06eba..701aff9c 100644 --- a/stdlib/patterns.c +++ b/stdlib/patterns.c @@ -7,6 +7,7 @@ #include "arrays.h" #include "integers.h" +#include "optionals.h" #include "patterns.h" #include "tables.h" #include "text.h" @@ -824,10 +825,19 @@ PUREFUNC public bool Text$has(Text_t text, Pattern_t pattern) } } -PUREFUNC public bool Text$matches(Text_t text, Pattern_t pattern) +public OptionalArray_t Text$matches(Text_t text, Pattern_t pattern) { - int64_t m = match(text, 0, pattern, 0, NULL, 0); - return m == text.length; + capture_t captures[MAX_BACKREFS] = {}; + int64_t match_len = match(text, 0, pattern, 0, captures, 0); + if (match_len != text.length) + return NULL_ARRAY; + + Array_t capture_array = {}; + for (int i = 0; captures[i].occupied; i++) { + Text_t capture = Text$slice(text, I(captures[i].index+1), I(captures[i].index+captures[i].length)); + Array$insert(&capture_array, &capture, I(0), sizeof(Text_t)); + } + return capture_array; } public Array_t Text$find_all(Text_t text, Pattern_t pattern) diff --git a/stdlib/patterns.h b/stdlib/patterns.h index 804fb286..9825cf96 100644 --- a/stdlib/patterns.h +++ b/stdlib/patterns.h @@ -21,7 +21,7 @@ Text_t Text$trim(Text_t text, Pattern_t pattern, bool trim_left, bool trim_right Int_t Text$find(Text_t text, Pattern_t pattern, Int_t i, int64_t *match_length); Array_t Text$find_all(Text_t text, Pattern_t pattern); PUREFUNC bool Text$has(Text_t text, Pattern_t pattern); -PUREFUNC bool Text$matches(Text_t text, Pattern_t pattern); +Array_t Text$matches(Text_t text, Pattern_t pattern); Text_t Text$map(Text_t text, Pattern_t pattern, Closure_t fn); #define Pattern$hash Text$hash -- cgit v1.2.3