Home »
Compiler Design
LEX Code to identify and print valid Identifier of C/C++ in given Input pattern
In this article, we going to learn how to create LEX program to analysis whether a input is identifier or not?
Submitted by Ashish Varshney, on March 24, 2018
For achieve to this task we create some rules in rule section in the code.
Example:
Input: var
Output: Identifier
Input: 123
Output: Not a Identifier
/*Definition Section*/
%{
#include<stdio.h>
%}
/*Rule Section*/
%%
/*put all words in a single line, which are broken in 4 lines*.
auto|double|int|struct|break|else|long|switch|case|
enum|register|typedef|char|extern|return|union|continue
|for|signed|void|do|if|static|while|default|goto|sizeof
|volatile|const|float|short|unsigned;
/*Check the token, if token is match with
pattern then it will print identifier.*/
([a-zA-Z][0-9])+|[a-zA-Z]* {printf("Identifier\n");}
^[0-9]+ {printf("Not a Identifier\n");}
.|\n;
%%
/*call the yywrap function*/
int yywrap()
{
return 1;
}
/*Auxiliary function*/
/*Driver function*/
int main(void)
{
/*call the yylex function.*/
yylex();
return 0;
}