What are LEX programs? How to write them?

LEX programs are used in “Lexical analysis” of the input stream, which is to break the input stream into usable and meaningful elements. The job of a lexical analyzer is to identify and match the patterns from the input stream with respect to the rule part mentioned in the LEX program.

Structure of a LEX program

. lex/struct

The LEX structure consists of 4 different sections, they are as follows –

  • DECLARATION PART – This section starts with ‘%{‘ , ends with ‘}%’ and includes the libraries like stdio.h which are to be included before executing the LEX program. We can also declare variables in this section that can be used in the rule part.
  • DEFINITION PART – This section follows the declaration part and is written in between the definition part and the rule part. It is used to define patterns which can be assessed by the rule part.
  • RULE PART – This section starts with ‘%%’  and ends with ‘%%’. Rule part the necessary and the most important part of a LEX program, it gives the rule according to which the patterns are matched and the associated action is undertaken by the LEX program.
  • USER DEFINED PART – This section is the basic sequence of flow for a LEX program, this section can be used to take input from the user or to print some data on to the terminal/console and is written in C.

 

Writing your first LEX Program

Now let’s write our first LEX program, in this program we will checker whether the entered character is a vowel or a consonant and give the filename as vowel-consonant.l

%{
#include <stdio.h>
%}

/* The Rules */
%%
[aeiou]  {printf("Vowel");exit(0);}
[^aeiou] {printf("Consonant");exit(0);}
%%

void yywrap(){}

int main()
{
printf("\n Enter an alphabet:\n");
getchar();
/* This function does the lexical analysis */
yylex();
return 0;
}

So you have now written the program and wondering how do you even run it, it’s quite easy to do in a linux based machine by following these simple commands –

lex vowel-consonant.l
cc lex.yy.cc
./a.out

I will be covering more such interesting LEX program in future posts, so stay tuned ;)

Leave a Comment