You are on page 1of 13

Example 12

This lex specification program also can be used from find no of lines, words and
characters in a given file. Here, yyleng indicates the length of the string yytext.

%{
int lines=0,words=0,characters=0;
%}
word [^ \t\n]+
eol \n
%%
{word} {words++;characters+=yyleng;}
{eol} {characters++;lines++;}
. { characters++; }
%%
int main()
{
yylex();
printf("%d %d %d \n",lines,words,characters);
}

Some versions of Lex (or Flex), require the user to provide a


procedure called yywrap(), which is to be called for housekeeping
at the end of the source code. So, to be sure, add as the last line of
your input to Lex : int yywrap(){}.
for example : int yywrap (void) {return 1;}

Example LEX

Objective:
.
%{
int pi=0,ni=0,pf=0,nf=0;
%}
%%

\+?[0-9]+ pi++;
\+?[0-9]*\.[0-9]+ pf++;
\-[0-9]+ ni++;
\-[0-9]*\.[0-9]+ nf++;
%%
main()
{
printf("ENTER INPUT : ");
yylex();
printf("\nPOSITIVE INTEGER : %d",pi);
printf("\nNEGATIVE INTEGER : %d",ni);
printf("\nPOSITIVE FRACTION : %d",pf);
printf("\nNEGATIVE FRACTION : %d\n",nf);
}

Example LEX

Objective: Lex program to check the validity of arithematic statement.

%{
#include<stdio.h>
int opr=0,opd=0;
int n;
%}
%%

[\+\-\*\/] { printf("OPERATORS ARE %s\n",yytext);


opr++;
}
[a-zA-Z]+ { printf("OPERANDS ARE %s\n",yytext);
opd++;
}
[0-9]+ { printf("OPERANDS ARE %s\n",yytext);
opd++;
}
[a-zA-Z]+\+\-\*\/[a-zA-Z]+ { n=0; }
[0-9]+\+\-\*\/[0-9]+ { n=0; }
%%

main()
{
printf("\nENTER THE EXPRESSION : \n");
yylex();
printf("\nNUMBER OF OPERATORS ARE %d",opr);
printf("\nNUMBER OF OPERANDS ARE %d",opd);
if((n==0)&&(opd==opr+1))
printf("\nVALID EXPRESSION\n");
else
printf("\nINVALID EXPRESSION\n");
}

Example LEX
>> before doing this, try the above example-5 (Slide) to illustrate the comments starting from //
>> this program checks the comments of /* . . . . */
This program is an attempt to extract only comments from
a C program and display the same on standard output
%{
%}
comment \/\*.*\*\/
%%
{comment} ECHO;
%%
main(int argc, char*argv[])
{
extern FILE *yyin;
yyin=fopen(argv[1],"r");
yylex();
printf("\n");
return 0;
}

Example LEX
Objective: Lex program to check the validity of arithematic statement.

%{
#include<stdio.h>
int opr=0,opd=0;
int n;
%}
%%
[\+\-\*\/] { printf("OPERATORS ARE %s\n",yytext);
opr++;
}

[a-zA-Z]+ { printf("OPERANDS ARE %s\n",yytext);


opd++;
}

[0-9]+ { printf("OPERANDS ARE %s\n",yytext);


opd++;
}

[a-zA-Z]+\+\-\*\/[a-zA-Z]+ { n=0; }
[0-9]+\+\-\*\/[0-9]+ { n=0; }
%%

void main()
{
printf("\nENTER THE EXPRESSION : \n");
yylex();
printf("\nNUMBER OF OPERATORS ARE %d",opr);
printf("\nNUMBER OF OPERANDS ARE %d",opd);
if((n==0)&&(opd==opr+1))
printf("\nVALID EXPRESSION\n");
else
printf("\nINVALID EXPRESSION\n");
}

You might also like