xs_regex.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* copyright (c) 2022 grunfink - MIT license */
  2. #ifndef _XS_REGEX_H
  3. #define _XS_REGEX_H
  4. d_char *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, 0xfffffff)
  6. d_char *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, 0xfffffff)
  8. #ifdef XS_IMPLEMENTATION
  9. #include <regex.h>
  10. d_char *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. d_char *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_str_cat(list, "");
  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_str_cat(list, "");
  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. d_char *xs_regex_match_n(const char *str, const char *rx, int count)
  38. /* returns a list with upto count matches */
  39. {
  40. d_char *list = xs_list_new();
  41. xs *split = NULL;
  42. char *p, *v;
  43. int n = 0;
  44. /* split */
  45. p = split = xs_regex_split_n(str, rx, count);
  46. /* now iterate to get only the 'separators' (odd ones) */
  47. while (xs_list_iter(&p, &v)) {
  48. if (n & 0x1)
  49. list = xs_list_append(list, v);
  50. n++;
  51. }
  52. return list;
  53. }
  54. #endif /* XS_IMPLEMENTATION */
  55. #endif /* XS_REGEX_H */