diff options
Diffstat (limited to 'examples/regex_match.c')
| -rw-r--r-- | examples/regex_match.c | 43 |
1 files changed, 20 insertions, 23 deletions
diff --git a/examples/regex_match.c b/examples/regex_match.c index 72039fde..1e87affb 100644 --- a/examples/regex_match.c +++ b/examples/regex_match.c @@ -1,38 +1,35 @@ #define i_implement #include <stc/cstr.h> #include <stc/cregex.h> +#define i_val float +#include <stc/cstack.h> int main() { // Lets find the first sequence of digits in a string - const char *s = "Hello numeric world, there are 24 hours in a day, 3600 seconds in an hour." - " Around 365.25 days a year, and 52 weeks in a year." - " Boltzmann const: 1.38064852E-23, is very small." - " Bohrradius is 5.29177210903e-11, and Avogadros number is 6.02214076e23."; + const char *str = "Hello numeric world, there are 24 hours in a day, 3600 seconds in an hour." + " Around 365.25 days a year, and 52 weeks in a year." + " Boltzmann const: 1.38064852E-23, is very small." + " Bohrradius is 5.29177210903e-11, and Avogadros number is 6.02214076e23."; c_auto (cregex, re) + c_auto (cstack_float, vec) + c_auto (cstr, nums) { - int res = cregex_compile(&re, "[+-]?([0-9]*\\.)?\\d+([Ee][+-]?\\d+)?", 0); - printf("%d\n", res); - csview m[5]; - if (cregex_find(s, &re, m, 0) == 1) { - printf("Found digits at position %" PRIuMAX "-%" PRIuMAX "\n", m[0].str - s, m[0].str - s + m[0].size); - } else { - printf("Could not find any digits\n"); - } + const char* pattern = "[+-]?([0-9]*\\.)?\\d+([Ee][+-]?\\d+)?"; + int res = cregex_compile(&re, pattern, 0); + printf("%d: %s\n", res, pattern); - while (cregex_find(s, &re, m, cre_m_next) == 1) { - printf("%.*s ; ", c_ARGsv(m[0])); - } - puts(""); + // extract and convert all numbers in str to floats + c_foreach_match (i, &re, str) + cstack_float_push(&vec, atof(i.ref->str)); - res = cregex_compile(&re, "(.+)\\b(.+)", 0); - printf("groups: %d\n", res); - if ((res = cregex_find("hello@wørld", &re, m, 0)) == 1) { - c_forrange (i, res) - printf("match: [%.*s]\n", c_ARGsv(m[i])); - } else - printf("err: %d\n", res); + c_foreach (i, cstack_float, vec) + printf(" %g\n", *i.ref); + + // extracts the numbers only to a comma separated string. + nums = cregex_replace_ex(str, &re, " $0,", 0, cre_r_strip, NULL); + printf("\n%s\n", cstr_str(&nums)); } } |
