Posted by: sirivy | March 28, 2009

Lex Simple Example

CODE: Reference from LEX & YACC books

========================

%{
char* yytext;
%}
%%
[\t]+ /*ignore whitespace*/;

is |
am |
are |
were |
was |
go      { printf(“%s:is a verb\n”,yytext);}

very |
simply |
gently |
quietly |
calmly |
angrily {printf(“%s: is and adverb\n”,yytext);}

to |
from |
behind |
above |
between |
below {printf(“%s: is a preposition\n”,yytext);}

if |
then |
and |
but |
or  { printf(“%s: is a conjunction\n”,yytext);}

their |
my |
your |
his |
her |
its {printf(“%s: is an adjective\n”,yytext);}

I |
you |
he |
she |
we |
they {printf(“%s: is a pronoun\n”,yytext);}

[a-zA-Z]+ {printf(“%s: is not a verb\n”,yytext);}

.|\n    {ECHO; /*normal default anyway*/}
%%

main()
{
yylex();
}

========================

This example code will scan input and if input match with pattern program will print type of each word.

*NOTE: In specifying pattern , you must have space before “|” symbol
(i.e.   is|   —>it  didn’t work You will meet unrecognized rule   BUT is  |  –>it works )


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: