Open In App

Lex program to check whether the input is digit or not

Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.

Prerequisite: Flex (Fast lexical Analyzer Generator).

Given an input, the task is to check if the input is digit or not.

Examples:

Input:  28
Output: digit

Input: a
Output: not a digit. 

Input: 21ab
Output: not a digit. 

Below is the implementation:




/* Lex program to check whether input is digit or not. */
%{
#include<stdio.h>
#include<stdlib.h>
%}
/* Rule Section */
%%
^[0-9]*  printf("digit");
^[^0-9]|[0-9]*[a-zA-Z]  printf("not a digit");
. ;
%%
int main()
{
        // The function that starts the analysis
    yylex();
        return 0;
}

Output:

Article Tags :