Lex Programming Lab
Lex Programming Lab
1. Definition Section
2. Rules Section
3. Auxiliary Section
Definition section
%%
Rules section
%%
Auxiliary section
The first two sections are necessary, even if they are empty. The third part and the
preceding %% line may be omitted.
Definition Section
The Definition Section contains user-defined Lex options used by the lexer. It creates
an environment for the execution of the Lex program and can be empty. This section
helps in two ways:
Rules Section
The Rules Section contains the patterns and actions that define the Lex
specifications:
● Patterns:
○ Formed by regular expressions to match the largest possible string.
● Actions:
○ Enclosed in braces {}.
○ Contain normal C language statements.
○ When a pattern is matched, the corresponding action is invoked.
○ The lexer tries to match the largest possible string. If two rules match
the same length, the lexer uses the first rule to invoke its corresponding
action.
Auxiliary Section
Lex Variables
● yyin:
○ Type: FILE*
○ Points to the current input file.
● yyout:
○ Type: FILE*
○ Points to the output location.
● yytext:
○ Stores the text of the matched pattern in a variable.
● yylen:
○ Gives the length of the matched pattern.
Lex Functions
● yywrap:
○ Called when the end of the input file is encountered.
○ Can be used to parse multiple input files.
● yylex(int n):
○ Can be used to push back all but the first n characters of the read
token.
● yymore:
○ Keeps the token’s lexeme in yytext when another pattern is matched.
Lex Macros
● Letter: [a-zA-Z]
● Digit: [0-9]
● Identifier: {letter}({letter}|{digit})
INTRODUCTION
❖ Firstly lexical analyzer creates a program lex.1 in the Lex language. Then Lex
compiler runs the lex.1 program and produces a C program lex.yy.c.
❖ Finally C compiler runs the lex.yy.c program and produces an object program
a.out.
❖ a.out is lexical analyzer that transforms an input stream into a sequence of
tokens.
yylex(): The main Lex function that performs lexical analysis and matches patterns in the
input.
yytext: A pointer to the matched text (a string) for the current pattern.
yyleng: The length of the matched text in yytext.
yyin: A file pointer that indicates the input stream (defaults to stdin).
yyout: A file pointer for output (defaults to stdout).
yywrap(): A function called when the end of input is reached; by default, returns 1 to
indicate end of input.
Experiment-1a: LEX program to count the number of lines, words
and characters in an input and input from a file.
Countchlw.l
OUTPUT:
Experiment-1b: LEX program to count number of words, lines
and characters from file
Countfilech.l
OUTPUT:
Experiment-2: LEX program to identify and Count Positive and
Negative Numbers.
Countnp.l
OUTPUT:
Experiment-3: LEX program to count the number of vowels and
consonants.
Countvc.l
OUTPUT
Experiment-4: LEX program to remove space, tab or newline.
rmstn.l
OUTPUT
Experiment-5: LEX program to find the length of a string.
strlen.l
OUTPUT