Howdy guys,
Lets have a look on how a Lex programs works using a simple example.
This sample programs counts the number of lines, words and characters in a text file.
Lex programming is not rocket science. You have to just apply an eight year old kid's logic. Yes, you read right. Only a school kid's logic.
LOGIC
Read each character from the text file :
- Is it a capital letter in English? [A-Z] : increment capital letter count by 1.
- Is it a small letter in English? [a-z] : increment small letter count by 1
- Is it [0-9]? increment digit count by 1.
- All other characters (like '!', '@','&') are counted as special characters
- How to count the number of lines? we simply count the encounters of '\n' <newline> character.that's all!!
- To count the number of words we count white spaces and tab character(of course, newline characters too..)
Alignment of a Lex program is very simple and it makes the logic more vivid.
counter.l
%{
#include<stdio.h>
int lines=0, words=0,s_letters=0,c_letters=0, num=0, spl_char=0,total=0;
%}
%%
\n { lines++; words++;}
[\t ' '] words++;
[A-Z] c_letters++;
[a-z] s_letters++;
[0-9] num++;
. spl_char++;
%%
main(void)
{
yyin= fopen("myfile.txt","r");
yylex();
total=s_letters+c_letters+num+spl_char;
printf(" This File contains ...");
printf("\n\t%d lines", lines);
printf("\n\t%d words",words);
printf("\n\t%d small letters", s_letters);
printf("\n\t%d capital letters",c_letters);
printf("\n\t%d digits", num);
printf("\n\t%d special characters",spl_char);
printf("\n\tIn total %d characters.\n",total);
}
int yywrap()
{
return(1);
}
Sample output
Let the 'myfile.txt' contains this.
This is my 1st lex program!!!
Cheers!! It works!!:)
The output will be
This file contains..
2 lines
9 words
30 small letters
3 capital letters
1 digits
9 special characters
In total 43 characters.