0% found this document useful (0 votes)
2 views2 pages

Math Expression Tokenizer in Lex

The Lex program functions as a tokenizer for simple math expressions, identifying tokens such as numbers, operators, parentheses, and whitespace. It uses regular expressions to match different components of the input expression and prints them accordingly. The program prompts the user to enter a math expression and processes it to display the identified tokens.

Uploaded by

Prajyot06
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Math Expression Tokenizer in Lex

The Lex program functions as a tokenizer for simple math expressions, identifying tokens such as numbers, operators, parentheses, and whitespace. It uses regular expressions to match different components of the input expression and prints them accordingly. The program prompts the user to enter a math expression and processes it to display the identified tokens.

Uploaded by

Prajyot06
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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 )

You might also like