fork(1) download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <regex.h>
  4.  
  5. struct token_t {
  6. char *name;
  7. char *pattern;
  8. regex_t regex;
  9. };
  10.  
  11. #define TOKEN_ENTRY(name, regex) { #name, regex }
  12. #define ARRAYOF(array) (sizeof(array) / sizeof(*array))
  13.  
  14. struct token_t g_token[] = {
  15. TOKEN_ENTRY(number, "^[-+]?[0-9]+$"),
  16. TOKEN_ENTRY(string, ".*"),
  17. };
  18.  
  19. int initialize_token()
  20. {
  21. int index;
  22. for (index = 0; index < ARRAYOF(g_token); index++)
  23. if (regcomp(&g_token[index].regex, g_token[index].pattern,
  24. REG_EXTENDED | REG_NEWLINE) < 0)
  25. return -1;
  26. return 0;
  27. }
  28.  
  29. void finalize_token()
  30. {
  31. int index;
  32. for (index = 0; index < ARRAYOF(g_token); index++)
  33. regfree(&g_token[index].regex);
  34. }
  35.  
  36. int get_token_index(char *string)
  37. {
  38. regmatch_t match[1];
  39. int index;
  40. for (index = 0; index < ARRAYOF(g_token); index++)
  41. if (!regexec(&g_token[index].regex, string, 1, match, 0))
  42. return index;
  43. return -1;
  44. }
  45.  
  46. char *get_token_name(char *string)
  47. {
  48. int index;
  49. index = get_token_index(string);
  50. return index != -1 ? g_token[index].name : "null";
  51. }
  52.  
  53. #define print(string) printf(string " = %s\n", get_token_name(string))
  54.  
  55. void do_run_while_ctrl_d()
  56. {
  57. static char buffer[BUFSIZ];
  58. char *ptr;
  59.  
  60. buffer[sizeof(buffer) - 1] = '\0';
  61. while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
  62. ptr = strchr(buffer, '\n');
  63. if (ptr == NULL) {
  64. fprintf(stderr, "Too long string (buffer size = %u)\n",
  65. (unsigned int) sizeof(buffer) - 1);
  66. return;
  67. }
  68. *ptr = '\0';
  69. printf("%s\n", get_token_name(buffer));
  70. }
  71. }
  72.  
  73. int main(int argc, char *argv[])
  74. {
  75. initialize_token();
  76. do_run_while_ctrl_d();
  77. finalize_token();
  78. return 0;
  79. }
  80.  
Success #stdin #stdout 0s 2436KB
stdin
1234
1234abncdef
ab^d34x
-92837
+37
stdout
number
string
string
number
number