summaryrefslogtreecommitdiffhomepage
path: root/misc/tests
diff options
context:
space:
mode:
authorTyge Løvset <[email protected]>2023-01-22 16:22:51 +0100
committerTyge Løvset <[email protected]>2023-01-22 16:22:51 +0100
commitaf74e5f44af8f03ec3b0b2ffd3fd577210707e49 (patch)
tree5905f4c80190161cdc9f814e78a7a87030cae1c7 /misc/tests
parent01bffb4d3b6b175db264c5cc30b1b7e756560639 (diff)
downloadSTC-modified-af74e5f44af8f03ec3b0b2ffd3fd577210707e49.tar.gz
STC-modified-af74e5f44af8f03ec3b0b2ffd3fd577210707e49.zip
Added cspan_init() for static initializing and a minor fix. Added cregex replace tests.
Diffstat (limited to 'misc/tests')
-rw-r--r--misc/tests/cregex_test.c47
1 files changed, 47 insertions, 0 deletions
diff --git a/misc/tests/cregex_test.c b/misc/tests/cregex_test.c
index 8ac268f1..bd13d16a 100644
--- a/misc/tests/cregex_test.c
+++ b/misc/tests/cregex_test.c
@@ -233,3 +233,50 @@ CTEST(cregex, captures_cap)
ASSERT_TRUE(cregex_is_match(&re, "abcdcdcd"));
}
}
+
+static bool add_10_years(int i, csview match, cstr* out) {
+ if (i == 1) { // group 1 matches year
+ int year;
+ sscanf(match.str, "%4d", &year); // scan 4 chars only
+ cstr_printf(out, "%04d", year + 10);
+ return true;
+ }
+ return false;
+}
+
+CTEST(cregex, replace)
+{
+ const char* pattern = "\\b(\\d\\d\\d\\d)-(1[0-2]|0[1-9])-(3[01]|[12][0-9]|0[1-9])\\b";
+ const char* input = "start date: 2015-12-31, end date: 2022-02-28";
+
+ c_AUTO (cstr, str) {
+ /* replace with a fixed string, extended all-in-one call: */
+ cstr_take(&str, cregex_replace_pattern(pattern, input, "YYYY-MM-DD"));
+ ASSERT_TRUE(cstr_equals(&str, "start date: YYYY-MM-DD, end date: YYYY-MM-DD"));
+
+ /* US date format, and add 10 years to dates: */
+ cstr_take(&str, cregex_replace_pattern_ex(pattern, input, "$1/$3/$2", 0, add_10_years, CREG_DEFAULT));
+ ASSERT_TRUE(cstr_equals(&str, "start date: 2025/31/12, end date: 2032/28/02"));
+
+ /* Wrap first date inside []: */
+ cstr_take(&str, cregex_replace_pattern_ex(pattern, input, "[$0]", 1, NULL, CREG_DEFAULT));
+ ASSERT_TRUE(cstr_equals(&str, "start date: [2015-12-31], end date: 2022-02-28"));
+
+ /* Wrap all words in ${} */
+ cstr_take(&str, cregex_replace_pattern("[a-z]+", "52 apples and 31 mangoes", "$${$0}"));
+ ASSERT_TRUE(cstr_equals(&str, "52 ${apples} ${and} 31 ${mangoes}"));
+
+ /* Compile RE separately */
+ c_WITH (cregex re = cregex_from(pattern, CREG_DEFAULT), cregex_drop(&re)) {
+ ASSERT_EQ(cregex_captures(&re), 4);
+
+ /* European date format. */
+ cstr_take(&str, cregex_replace(&re, input, "$3.$2.$1"));
+ ASSERT_TRUE(cstr_equals(&str, "start date: 31.12.2015, end date: 28.02.2022"));
+
+ /* Strip out everything but the matches */
+ cstr_take(&str, cregex_replace_sv(&re, csview_from(input), "$3.$2.$1;", 0, NULL, CREG_R_STRIP));
+ ASSERT_TRUE(cstr_equals(&str, "31.12.2015;28.02.2022;"));
+ }
+ }
+}