Microsoft Word - Lab - Compiler11-15
Microsoft Word - Lab - Compiler11-15
/* float1.l */
%option main
digit [0-9]
%%
[+-]?{digit}*(\.)?{digit}+ printf("FLOAT");
Input Output
ali-7.8veli ali>-7.800000<veli
ali--07.8veli ali->-7.800000<veli
+3.7.5 >3.700000<>0.500000<
Other examples
/* echo-upcase-wrods.l */
%option main
%%
[A-Z]+[ \t\n\.\,] printf("%s",yytext);
. ; /* no action specified */
The scanner for the specification above echo all strings of capital letters, followed by a space tab
(\t)or newline (\n) dot (\.) or comma (\,) to stdout, and all other characters will be ignored.
Input Output
Ali VELI A7, X. 12 VELI X
HAMI BEY a HAMI BEY
If more than one regular expression matches the same string the one that is defined earlier is
used.
Example,
/* rule-order.l */
%option main
%%
for printf("FOR");
[a-z]+ printf("IDENTIFIER");
for input
for count := 1 to 10
the output would be
FOR IDENTIFIER := 1 IDENTIFIER 10
Note: Do not leave extra spaces and/or empty lines at the end of the lex specification file.
Practical 6
Implement following programs using Lex.
1. Create a Lexer to take input from text file and count no of characters, no. of lines
& no. of words.
2. Write a Lex program to count number of vowels and consonants in a given input
string.
Source code 1:
%{
int charCount = 0, lineCount = 0, wordCount = 0;
%}
%%
. charCount++;
[A-Za-z]+ {charCount += yyleng, wordCount++;}
\n {charCount++, lineCount++, wordCount++;}
%%
int main(){
yyin = fopen("test.txt", "r");
yylex();
printf("there are %d char, %d words and %d lines", charCount,
wordCount,
lineCount);
return 0;
}
test.txt:
hi
how are you
fine
you
very fine
good
Output:
~
[stu1@ARS ~]$ gcc lex.yy.c -ll
[stu1@ARS ~]$ ./a.out
there are 40 char, 15 words and 6 lines[stu1@ARS ~]$
Source code 2:
%{
#include<stdio.h>
#include<stdlib.h>
%%
[^aeiouAEIOU] consonent++;
[aeiouAEIOU] vowel++;
%%
int main() {
yyin = fopen("lab6_input.txt", "r");
yylex();
printf("There are %d vowels and %d consonents\n", vowel,
consonent);
return 0;
test.txt:
Output:
Source code 1:
%{
#include<stdio.h>
#include<stdlib.h>
int countNumber = 0;
%}
%%
[0-9]+ {printf("%s\n", yytext); countNumber++;}
[^0-9] {printf("");}
%%
int main() {
yyin = fopen("lab7_a_input.txt", "r");
yylex();
printf("There are total %d numbers in the file\n", countNumber);
return 0;
}
lab7_a_input.txt.txt:
hello 678
call me on 34508
and if i dont respond then call on 276472
thank you 678
regards 123
thanks
Output: