A simple program of LEX
/** Definition section **/ %{ #include <stdio.h> %} %option noyywrap %% /** Rules section **/ /* [0-9]+ matches a string of one or more digits */ [0-9]+ { /* yytext is a string containing the matched text. */ printf("Saw an integer: %s\n", yytext); } .|\n { /* Ignore other characters. */ } %% /** C Code section **/ int main(void) { /* Call the lexer */ yylex(); return 0; }
steps to execute
1. lex filename.l
2. cc ley.yy.c
3. ./a.out
<<<THEORY ABOUT LEX PROGRAM>>>
1)check whether flex
or flex-old is installed or not
2)if it is not
installed use following command
sudo apt-get
install flex
structure
of lex file
it contains 3 diff.
sections as follows:
1)Definition
section which written in %{.....%}
2)Rule Section
which is enclosed between %%....%%
it is assosiated
with regular expression patterns with C statements.
3)Code section
which contains C
statements and functions required to execute Lex file.
Execution
of lex program
By
using structure of lex program create lex file with .l as extension.
Step-1:
lex filename.l
it
will check whether lex program is lexically correct or not.
If
it contains some errors we need to recompile the file using the same
command.
Step-2: cc
lex.yy.c
it
converts the lex program into a C program name as lex.yy.c
This
lex.yy.c file is
executable
Step-3: ./a.out
This command will execute lex.yy.c file.
Metachar
|
Matches |
. |
Any character except new line. |
/n |
New line. |
* |
Zero or more copies of preceding expression |
+ |
One or more copies of preceding expression |
? |
Zero or one copies of preceding expression |
$ |
End of line |
(ab)+ |
One or more copies of ab together |
^ |
Beggining of line. |
“a+b” |
Literal a+b |
[] |
Character class. |
Table: pattern matching premitives
expression |
Matches |
abc |
a,b,c |
abc* |
ab,abc,abcc,abccc ...... |
abc+ |
abc,abcc...... |
a(bc)+ |
abc,abcbc,abcbcbc..... |
abc
|
one of (a b c) |
a/z |
Any character from a to z. |
a(bc)^? |
abc,a |
Table:pattern
matching Examples
Comments
Post a Comment