Lex Program to recognize comments, numbers, identifiers, and strings

 

Lex Program to recognize and display comments, numbers, identifiers, and strings in a given statement

Problem definition:

Write a lex program to recognize comments, numbers, identifiers, and strings in a given statement and display them on standard output.

Structure of LEX Program:

%{
Definition section
%}

%%
Rules section
%%

User Subroutine section  

Click here to know – How to Compile & Run LEX / YACC Programs on Windows 8, 10, and 11?

Source Code to recognize and display comments, numbers, identifiers, and strings

/*Definition Section*/
%{
#include<stdio.h>
%}

/* Rules Section */
%%
[\t ]+ ;
[0-9]+|[0-9]*\.[0-9]+ { printf("\n%s is NUMBER", yytext);}
#.* { printf("\n%s is COMMENT", yytext);}
[a-zA-Z][a-zA-Z0-9]+ { printf("\n%s is IDENTIFIER", yytext);}
\"[^ \"\n]*\" { printf("\n%s is STRING", yytext);}
\n { ECHO;}
%%

/* User Subroutine section */
int main()
{
	while( yylex());
}

int yywrap( )
{
	return 1;
}

Alternate source code (display result in the main part of code)

/*Definition Section*/
%{
#include<stdio.h>
#define NUMBER 400
#define COMMENT 401
#define STRINGS 402
#define IDENTIFIER 403
%}

/* Rules Section */
%%
[\t  ]+     ;
[0-9]+ | [0-9]*\.[0-9]+ { return NUMBER;}
#.* 			{ return COMMENT;}
\"[^ \"\n]*\"      	{ return STRINGS;}
[a-zA-Z][a-zA-Z0-9]+	{ return IDENTIFIER;}
\n			{ return '\n';}
%%

/* User Subroutine section */
main( )
{
	int val;
	while( val = yylex( ))
	printf("value is %d\n",val);
}

int yywrap( )
{
	return 1;
}

Output:

maheshgh@maheshgh:~/LexYacc$ lex demo.l

maheshgh@maheshgh:~/LexYacc$ gcc lex.yy.c

maheshgh@maheshgh:~/LexYacc$ ./a.out

Mahesh Huddar

(Note: After every input string press enter and ctrl+d)

Mahesh: is IDENTIFIER

Huddar: is IDENTIFIER

10 10.20

10: is NUMBER

10.20 is NUMBER

#Mahesh Huddar

Mahesh Huddar: is COMMENT

“Mahesh Huddar”

“Mahesh Huddar”: is STRING

Summary:

This article discusses how to write a lex program to find comments, numbers, identifiers, and strings in a given statement and display them on standard output.. If you like the article, do share it with your friends.

Leave a Comment

Your email address will not be published. Required fields are marked *

Welcome to VTUPulse.com


Computer Graphics and Image Processing Mini Projects -> Click Here

Download Final Year Project -> Click Here

This will close in 12 seconds