PageRenderTime 40ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/c/snippets/regex.c

https://github.com/bashwork/common
C | 51 lines | 29 code | 4 blank | 18 comment | 27 complexity | 7b8cc4e940c5a652a7762da440aff6c7 MD5 | raw file
Possible License(s): GPL-2.0
  1. #include <stdio.h>
  2. #include "regex.h"
  3. /**
  4. *
  5. * @param regexp The regular expression to match with
  6. * @param text The text to match against the regexp
  7. * @return 1 if a match was found, 0 otherwise
  8. */
  9. int match(char *regexp, char *text) {
  10. if (regexp[0] == '^')
  11. return matchhere(regexp + 1, text);
  12. do {
  13. if (matchhere(regexp, text))
  14. return 1;
  15. } while (*text++ != '\0');
  16. return 0;
  17. }
  18. /**
  19. *
  20. * @param regexp The regular expression to match with
  21. * @param text The text to match against the regexp
  22. * @return 1 if a match was found, 0 otherwise
  23. */
  24. int matchstar(int c, char *regexp, char *text) {
  25. do {
  26. if (matchhere(regexp, text))
  27. return 1;
  28. } while (*text != '\0' && (*text++ == c || c == '.'));
  29. return 0;
  30. }
  31. /**
  32. *
  33. * @param regexp The regular expression to match with
  34. * @param text The text to match against the regexp
  35. * @return 1 if a match was found, 0 otherwise
  36. */
  37. int matchhere(char *regexp, char *text) {
  38. if (regexp[0] == '\0')
  39. return 1;
  40. if (regexp[0] == '*')
  41. return matchstar(regexp[0], regexp + 2, text);
  42. if (regexp[0] == '$' && regexp[1] == '\0')
  43. return (*text == '\0');
  44. if (*text != '\0' && (regexp[0] == '.' || regexp[0] == *text))
  45. return matchhere(regexp + 1, text + 1);
  46. return 0;
  47. }