Lex Program: Syntax Detective (Math Expression Tokenizer)
This Lex program acts like a tokenizer for simple math expressions. It identifies each token
such as numbers, operators, parentheses, and whitespace from the input expression.
Lex Code
%{
#include <stdio.h>
%}
%%
[0-9]+ { printf("NUMBER\t\t%s\n", yytext); }
[+*/-] { printf("OPERATOR\t%s\n", yytext); }
"(" { printf("LPAREN\t\t%s\n", yytext); }
")" { printf("RPAREN\t\t%s\n", yytext); }
[ \t\n]+ { printf("WHITESPACE\t'%s'\n", yytext); }
. { printf("UNKNOWN\t\t%s\n", yytext); }
%%
int main() {
printf("Enter a simple math expression (e.g., 2 + 3 * (4 - 1)):\n");
yylex();
return 0;
}
Sample Input and Output
Input:
2 + 3 * (4 - 1)
Output:
NUMBER 2
WHITESPACE ' '
OPERATOR +
WHITESPACE ' '
NUMBER 3
WHITESPACE ' '
OPERATOR *
WHITESPACE ' '
LPAREN (
NUMBER 4
WHITESPACE ' '
OPERATOR -
WHITESPACE ' '
NUMBER 1
RPAREN )