Sunday, October 17, 2010

Simple lex program

Lex acts as a lexical analyzer which reads the input and converts strings in the source to tokens according to the regular expressions defined in the source.

Sample lex code - lexcode.l

%{
//definition section
#include <stdio.h>
%}

%%
//rules section
[0123456789]+ printf("NUMBER\n");
[a-zA-Z][a-zA-Z0-9]* printf("WORD\n");
%%

//user subroutings


Compilation

lex lexcode1.l
Creates lex.yy.c

cc lex.yy.c -o lexcode1 -lfl

Execution

./lexcode1

Sample inputs and their outputs

foo
WORD

bar
WORD

123
NUMBER

bar123
WORD

123bar
NUMBER
WORD

No comments :

Post a Comment