You are on page 1of 6

LEX Example 1

%{

int num_lines = 0, num_chars = 0;

%}

%%

\n ++num_lines; ++num_chars;

. ++num_chars;

%%

int main ()

yylex ();

printf ("There were %d lines and %d characters.\n",

num_lines, num_chars);

return 0;

}
LEX Example 2
%{

#include <stdio.h>

%}

%%

[0123456789]+ printf("NUMBER\n");

[a-zA-Z][a-zA-Z0-9]* printf("WORD\n");

%%

Example 2-2
%{

#include <stdio.h>

%}

%%

[0123456789]+ printf("NUMBER\n");

[a-zA-Z][a-zA-Z0-9]* printf("WORD\n");

.* printf("OTHER\n");

%%

Input file for Example 2


1234

d23fg

876

23sdfg67hj

******
Lex Example 3
%{

#include <stdio.h>

%}

%%

[a-zA-Z][a-zA-Z0-9]* printf("WORD ");

[a-zA-Z0-9\/.-]+ printf("FILENAME ");

\" printf("QUOTE ");

\{ printf("OBRACE ");

\} printf("EBRACE ");

; printf("SEMICOLON ");

\n printf("\n");

[ \t]+ /* ignore whitespace */;

%%

Input file for example 3


logging {

category lame-servers { null; };

category cname { null; };

};

zone "." {

type hint;

file "/etc/bind/db.root";

};
Lex Example 4
%{

#include <stdlib.h>

#define NUMBER 1

#define PLUS 2

#define MINUS 3

#define TIMES 4

#define DIVIDE 5

#define POWER 6

#define LEFT_PARENTHESIS 7

#define RIGHT_PARENTHESIS 8

#define END 9

float yylval;

%}

white [ \t]+

digit [0-9]

integer {digit}+

exponant [eE][+-]?{integer}

real {integer}("."{integer})?{exponant}?

%%
{white} { /* We ignore white characters */ }

{real} {

yylval=atof(yytext);

printf("yytext = %s yylval = %f\n", yytext, yylval);

return(NUMBER);

"+" return(PLUS);

"-" return(MINUS);

"*" return(TIMES);

"/" return(DIVIDE);

"^" return(POWER);

"(" return(LEFT_PARENTHESIS);

")" return(RIGHT_PARENTHESIS);

"\n" return(END);

%%

int main ()

int ret = 0;

while (ret != END ) {

ret = yylex ();

printf("ret = %d, yylval = %f\n", ret, yylval);

return 0;

}
Input file for Example 4
1+2*3

2.5*(3.2-4.1^2)

You might also like