fork download
  1.  
  2. #include <cstdio>
  3. #define CIF(expr) ((expr)
  4. #define CTHEN ?
  5. #define CELSE :
  6. #define CENDIF )
  7.  
  8. constexpr int match_here(const char*, const char*);
  9. constexpr int match_wildcard(int, const char*, const char*);
  10.  
  11. constexpr int match_end(const char* pat, const char* text)
  12. {
  13. return
  14. (
  15. CIF(match_here(pat, text)) CTHEN
  16. 1
  17. CELSE
  18. CIF(*text == '\0') CTHEN
  19. 0
  20. CELSE
  21. match_end(pat, text+1)
  22. CENDIF
  23. CENDIF
  24. );
  25. }
  26.  
  27. constexpr int match_here(const char* pat, const char *text)
  28. {
  29. return
  30. (
  31. CIF(pat[0] == '\0') CTHEN
  32. 1
  33. CELSE
  34. CIF(pat[1] == '*') CTHEN
  35. match_wildcard(pat[0], pat+2, text)
  36. CELSE
  37. CIF(pat[0] == '$' && pat[1] == '\0') CTHEN
  38. (*text == '\0')
  39. CELSE
  40. CIF(*text != '\0' && (pat[0] == '.' || pat[0] == *text)) CTHEN
  41. match_here(pat+1, text+1)
  42. CELSE
  43. 0
  44. CENDIF
  45. CENDIF
  46. CENDIF
  47. CENDIF
  48. );
  49. }
  50.  
  51. constexpr int match_wildcard(int c, const char* pat, const char* text)
  52. {
  53. return
  54. (
  55. CIF(match_here(pat, text)) CTHEN
  56. 1
  57. CELSE
  58. CIF(*text != '\0' && (*text == c || c == '.')) CTHEN
  59. match_wildcard(c, pat, text+1)
  60. CELSE
  61. 0
  62. CENDIF
  63. CENDIF
  64. );
  65. }
  66.  
  67.  
  68. constexpr int match(const char* pat, const char* text)
  69. {
  70. return
  71. (
  72. CIF(pat[0] == '^') CTHEN
  73. match_here(pat + 1, text)
  74. CELSE
  75. match_end(pat, text)
  76. CENDIF
  77. );
  78. }
  79.  
  80.  
  81. int main(int argc, char* argv[])
  82. {
  83. if (argc > 2)
  84. {
  85. const char* pat = argv[1];
  86. const char* text = argv[2];
  87. printf("pattern: %s\n", pat);
  88. printf("text: %s\n", text);
  89. printf("result: %d\n", match(pat, text));
  90. }
  91. else
  92. {
  93. printf("usage: %s <pattern> <text>\n", argv[0]);
  94. }
  95. return 0;
  96. }
  97.  
  98.  
Success #stdin #stdout 0s 2900KB
stdin
Standard input is empty
stdout
usage: ./prog <pattern> <text>