diff options
| author | Bruce Hill <bruce@bruce-hill.com> | 2024-09-16 15:12:54 -0400 |
|---|---|---|
| committer | Bruce Hill <bruce@bruce-hill.com> | 2024-09-16 15:12:54 -0400 |
| commit | 6d0f04375df942985292d0a6b6e487db9a09f3fa (patch) | |
| tree | cad6fbb4008240cf7280b77fa226f9518f44faac /stdlib | |
| parent | a9a21c40d91ea75066023854739c6a98a36c8a76 (diff) | |
Have Text:matches() return an optional array of matches
Diffstat (limited to 'stdlib')
| -rw-r--r-- | stdlib/patterns.c | 16 | ||||
| -rw-r--r-- | stdlib/patterns.h | 2 |
2 files changed, 14 insertions, 4 deletions
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 |
