Flex is a fast lexical analyzer generator that is used to build scanners that process text patterns using regular expressions. It is commonly applied in compiler construction, interpreters, and custom parsing tools to generate efficient lexical analyzers in C. This tutorial demonstrates how to install Flex lexical analyzer on Ubuntu 26.04.
Prepare environment
C compiler is required because Flex generates C source code. Make sure GCC compiler is installed before starting.
sudo apt install -y gcc
Install Flex
Start by refreshing the package index so the latest versions are available:
sudo apt update
Install Flex:
sudo apt install -y flex
After installation, verify that Flex is available by checking its version:
flex --version
Testing Flex
Create a new Flex specification file named main.l:
nano main.l
Insert the following content:
%{
#include <stdio.h>
%}
%%
[ \t\n]+ ;
[a-zA-Z]+ { printf("Word: %s\n", yytext); }
[0-9]+ { printf("Number: %s\n", yytext); }
. { printf("Unknown: %s\n", yytext); }
%%
int main(void) {
yylex();
return 0;
}
int yywrap(void) {
return 1;
}
This example defines a simple lexer that recognizes alphabetic words, numeric values, and unknown characters while skipping whitespace.
Convert the Flex specification into a C source file:
flex main.l
This produces lex.yy.c. Compile the generated file using the command:
gcc lex.yy.c -o test
Run executable by providing input through standard input:
echo 'Hello 42 world' | ./test
Expected output:
Word: Hello
Number: 42
Word: world
Uninstall Flex
If Flex is no longer needed, it can be removed along with unused dependencies with command:
sudo apt purge --autoremove -y flex
Leave a Comment
Cancel reply