fork download
  1. #include <stdio.h>
  2.  
  3. int matchstar(int c, char *regexp, char*text);
  4. int matchhere(char *regexp, char *text);
  5.  
  6. int match(char *regexp, char *text)
  7. {
  8. if (regexp[0] == '^')
  9. return matchhere(regexp+1, text);
  10. do {
  11. if (matchhere(regexp, text))
  12. return 1;
  13. } while (*text++ != '\0');
  14. return 0;
  15. }
  16.  
  17. int matchstar(int c, char *regexp, char*text)
  18. {
  19. do {
  20. if (matchhere(regexp, text))
  21. return 1;
  22. } while (*text != '\0' && (*text++ == c || c == '.'));
  23. return 0;
  24. }
  25.  
  26. int matchhere(char *regexp, char *text)
  27. {
  28. if (regexp[0] == '\0')
  29. return 1;
  30. if (regexp[1] == '*')
  31. return matchstar(regexp[0], regexp+2, text);
  32. if (regexp[0] == '$' && regexp[1] == '\0')
  33. return *text == '\0';
  34. if (*text != '\0' && (regexp[0] == '.' || regexp[0] == *text))
  35. return matchhere(regexp+1, text+1);
  36. return 0;
  37. }
  38.  
  39. void test(char *regexp, char *text, int expected)
  40. {
  41. int res = match(regexp, text);
  42. if (res == expected)
  43. printf("[ OK ]");
  44. else
  45. printf("[FAIL]");
  46. printf("\t/%s ~ %s\t", regexp, text);
  47. if (res)
  48. printf("matching");
  49. else
  50. printf("not matching");
  51. printf("\n");
  52. }
  53.  
  54. int main()
  55. {
  56. test("a..*bb.*cd", "aababbcd", 1);
  57. test("a..*bb.*cd", "abcd", 0);
  58. test("a..*bb.*cd", "aa.bxcxd", 0);
  59.  
  60. test("a.*.b.*c.*d", "abcd", 0);
  61. test("a.*.b.*c.*d", "aabcd", 1);
  62. test("a.*.b.*c.*d", "a.bcd", 1);
  63. test("a.*.b.*c.*d", "aa.bxcxd", 1);
  64. test("a.*.b.*c.*d", "aa.bxcd", 1);
  65.  
  66. return 0;
  67. }
  68.  
Success #stdin #stdout 0s 2160KB
stdin
Standard input is empty
stdout
[ OK ]	/a..*bb.*cd ~ aababbcd	matching
[ OK ]	/a..*bb.*cd ~ abcd	not matching
[ OK ]	/a..*bb.*cd ~ aa.bxcxd	not matching
[ OK ]	/a.*.b.*c.*d ~ abcd	not matching
[ OK ]	/a.*.b.*c.*d ~ aabcd	matching
[ OK ]	/a.*.b.*c.*d ~ a.bcd	matching
[ OK ]	/a.*.b.*c.*d ~ aa.bxcxd	matching
[ OK ]	/a.*.b.*c.*d ~ aa.bxcd	matching