lex program to eliminate single and multiline comments

 

 

 

%{
#include<stdio.h>
%}
%%
“//”([a-z]|[0-9]|[A-Z]|” “)*    {}
“/*”([a-z]|[0-9]|[A-Z]|” “\””\n”)+”*/”    {}
%%
main()
{
yylex();
return 0;
}
int yywrap()
{
}

Sample output

single line comment //testing
single line comment
test line /*multi*/
test line

lex program to recognize identifier, keyword and number

 

 

 

%{
#include<stdio.h>
%}
%%
if|else|while|int|switch|for|char    {printf(“keyword”);}
[a-z]([a-z]|[0-9])*    {printf(“identifier”);}
[0-9]*        {printf(“number”);}
.*    {printf(“invalid”);}
%%
main()
{
yylex();
return 0;
}
int yywrap()
{
}

Sample output

else
keyword
humble
identifier
9876
number

 

lex program to prepend line number to each line

 

%{
#include<stdio.h>
#include<string.h>
int ln=0;
%}
%%
“\n” {}
.* {ln++;fprintf(yyout,”\n%d:%s”,ln,yytext);}
%%
main()
{
yyin=fopen(“try1.txt”,”r”);
yyout=fopen(“try2.txt”,”w”);
yylex();
return 0;
}
int yywrap()
{
}

 

</pre>

Sample output

try1.txt

hai
hello world
test file
language processor

try2.txt

1:hai
2:hello world
3:test file
4:language processor