fork download
  1. %{
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. int op_flag = 0; // to detect two operators in a row
  6. int valid = 1; // assume valid until proven otherwise
  7. int balance = 0; // parenthesis balance counter
  8. %}
  9.  
  10. %%
  11.  
  12. [0-9]+ { op_flag = 0; } /* number */
  13. [a-zA-Z]+ { op_flag = 0; } /* identifier */
  14.  
  15. [+\-*/] {
  16. if(op_flag == 1) valid = 0; // two operators in a row
  17. op_flag = 1;
  18. }
  19.  
  20. "(" { balance++; op_flag = 0; }
  21. ")" { balance--; if(balance < 0) valid = 0; op_flag = 0; }
  22.  
  23. [ \t\n]+ ; /* ignore whitespaces */
  24.  
  25. . { valid = 0; } /* any other symbol → invalid */
  26.  
  27. %%
  28.  
  29. int main()
  30. {
  31. printf("Enter mathematical expression: ");
  32. yylex();
  33.  
  34. if(balance != 0)
  35. valid = 0;
  36.  
  37. if(valid)
  38. printf("\nValid Expression\n");
  39. else
  40. printf("\nInvalid Expression\n");
  41.  
  42. return 0;
  43. }
Success #stdin #stdout #stderr 0.02s 6824KB
stdin
(3+4)*5
stdout
Standard output is empty
stderr
ERROR: /home/Qyx97a/prog:2:1: Syntax error: Operator expected
ERROR: /home/Qyx97a/prog:43:0: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit