xs_regex.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* copyright (c) 2022 - 2023 grunfink et al. / MIT license */
  2. #ifndef _XS_REGEX_H
  3. #define _XS_REGEX_H
  4. xs_list *xs_regex_split_n(const char *str, const char *rx, int count);
  5. #define xs_regex_split(str, rx) xs_regex_split_n(str, rx, XS_ALL)
  6. xs_list *xs_regex_match_n(const char *str, const char *rx, int count);
  7. #define xs_regex_match(str, rx) xs_regex_match_n(str, rx, XS_ALL)
  8. #ifdef XS_IMPLEMENTATION
  9. #include <regex.h>
  10. xs_list *xs_regex_split_n(const char *str, const char *rx, int count)
  11. /* splits str by regex */
  12. {
  13. regex_t re;
  14. regmatch_t rm;
  15. int offset = 0;
  16. xs_list *list = NULL;
  17. const char *p;
  18. if (regcomp(&re, rx, REG_EXTENDED))
  19. return NULL;
  20. list = xs_list_new();
  21. while (count > 0 && !regexec(&re, (p = str + offset), 1, &rm, offset > 0 ? REG_NOTBOL : 0)) {
  22. /* add first the leading part of the string */
  23. list = xs_list_append_m(list, p, rm.rm_so);
  24. list = xs_insert_m(list, xs_size(list) - 1, "", 1);
  25. /* add now the matched text as the separator */
  26. list = xs_list_append_m(list, p + rm.rm_so, rm.rm_eo - rm.rm_so);
  27. list = xs_insert_m(list, xs_size(list) - 1, "", 1);
  28. /* move forward */
  29. offset += rm.rm_eo;
  30. count--;
  31. }
  32. /* add the rest of the string */
  33. list = xs_list_append(list, p);
  34. regfree(&re);
  35. return list;
  36. }
  37. xs_list *xs_regex_match_n(const char *str, const char *rx, int count)
  38. /* returns a list with upto count matches */
  39. {
  40. xs_list *list = xs_list_new();
  41. xs *split = NULL;
  42. xs_list *p;
  43. xs_val *v;
  44. int n = 0;
  45. /* split */
  46. split = xs_regex_split_n(str, rx, count);
  47. /* now iterate to get only the 'separators' (odd ones) */
  48. p = split;
  49. while (xs_list_iter(&p, &v)) {
  50. if (n & 0x1)
  51. list = xs_list_append(list, v);
  52. n++;
  53. }
  54. return list;
  55. }
  56. #endif /* XS_IMPLEMENTATION */
  57. #endif /* XS_REGEX_H */