You are on page 1of 10

What is Lex

Lex is a tool officially known for Lexical


Analaysis
It's main job is to break up an input stream
into more usable elements called as tokens.
Or in, other words, to identify the "interesting
bits" in a text file.
It uses regular expression matching; typically
to tokenize the contents of the file.
Lexical Analyzer
Lex Compiler
Lex.l
Lex.yy.c
Lex.yy.c
C Compiler
a.out
Structure of Lex
A lex file looks like

...definition section...
%%
...rules section...
%%
...code section...
Definition Section
%{
Definition Section
}%
The definition section, introduces any initial C
program code we want to copy into the final
program
For eg we want header files that must be
included for code later in the file to work

Lex copies the material between %{ and
}% directly to the generated C file (lex.yy.c)
The %% marks the end of this section
Rules Section
The rules section is made up of two parts:
A pattern
An Action separated by whitespace
The lexer that lex generates will execute the
action when it recognizes the pattern
These patterns are UNIX-style regular
expressions
The %% marks the end of this section


Code Section
The final section is the user subroutines
section or code section, which consist of any
legal C code.
Lex copies it to the C file after the end of the
lex geneated code
The lexer produced by lex is a C routine called
yylex().
Simple Lex Program
%{
/* simple C program*/
%}
%%
Hello" {
printf(Welcome");}

%%

You might also like