xs_regex.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* copyright (c) 2022 - 2023 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, XS_ALL)
  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, XS_ALL)
  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. split = xs_regex_split_n(str, rx, count);
  46. /* now iterate to get only the 'separators' (odd ones) */
  47. p = split;
  48. while (xs_list_iter(&p, &v)) {
  49. if (n & 0x1)
  50. list = xs_list_append(list, v);
  51. n++;
  52. }
  53. return list;
  54. }
  55. #endif /* XS_IMPLEMENTATION */
  56. #endif /* XS_REGEX_H */