a. Write a Lex program
to print out all numbers from the given file.
lex file: a.l
%{
intpostiveno=0;
intnegtiveno=0;
intpositivefractions=0;
intnegativefractions=0;
%}
DIGIT [0-9]
%%
\+?{DIGIT}+ postiveno++;
-{DIGIT}+ negtiveno++;
\+?{DIGIT}*\.{DIGIT}+ positivefractions++;
-{DIGIT}*\.{DIGIT}+ negativefractions++;
. ;
%%
main()
{
yylex();
printf("\nNo. of positive numbers: %d",postiveno);
printf("\nNo. of Negative numbers: %d",negtiveno);
printf("\nNo. of Positive fractions: %d",positivefractions);
printf("\nNo. of Negative fractions: %d\n",negativefractions);
}
Output:
nn@linuxmint ~ $ lexa.l
nn@linuxmint ~ $ gcclex.yy.c -ll
nn@linuxmint ~ $ ./a.out<a.txt
No. of positive numbers: 2
No. of Negative numbers: 3
No. of Positive fractions: 4
No. of Negative fractions: 5
nn@linuxmint ~ $
lex file: a.l
%{
intpostiveno=0;
intnegtiveno=0;
intpositivefractions=0;
intnegativefractions=0;
%}
DIGIT [0-9]
%%
\+?{DIGIT}+ postiveno++;
-{DIGIT}+ negtiveno++;
\+?{DIGIT}*\.{DIGIT}+ positivefractions++;
-{DIGIT}*\.{DIGIT}+ negativefractions++;
. ;
%%
main()
{
yylex();
printf("\nNo. of positive numbers: %d",postiveno);
printf("\nNo. of Negative numbers: %d",negtiveno);
printf("\nNo. of Positive fractions: %d",positivefractions);
printf("\nNo. of Negative fractions: %d\n",negativefractions);
}
Output:
nn@linuxmint ~ $ lexa.l
nn@linuxmint ~ $ gcclex.yy.c -ll
nn@linuxmint ~ $ ./a.out<a.txt
No. of positive numbers: 2
No. of Negative numbers: 3
No. of Positive fractions: 4
No. of Negative fractions: 5
nn@linuxmint ~ $
// Input file: a.txt
+12,-123,1.1,-1.1,12,-2,-3,2.1,3.2,5.1,-5.5,-6.1,-7.7,-8.8
b.Write a Lex program to printout all HTML tags in file
%{
#include<stdio.h>
%}
%%
(“<“|”<\\”)[a-z|A-Z|0-9]*”>” {printf(” “);}
%%
main()
{
yylex();
return 0;
}
+12,-123,1.1,-1.1,12,-2,-3,2.1,3.2,5.1,-5.5,-6.1,-7.7,-8.8
b.Write a Lex program to printout all HTML tags in file
%{
#include<stdio.h>
%}
%%
(“<“|”<\\”)[a-z|A-Z|0-9]*”>” {printf(” “);}
%%
main()
{
yylex();
return 0;
}
Output:
<html>test file<\html>
test file
test file
c.Write a Lex program which adds line
numbers to the given file and display the sameonto the standard output.
%{
#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;
}
Output:
#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;
}
Output:
try1.txt
hi
hello
test file
hello
test file
try2.txt
1:hi
2:hello
3:test file
2:hello
3:test file