Search code examples
regexlex

What is a regular expression for matching numbers divisible by 4?


I want to make a lexical analyzer that detects numbers divisible by 4.
Sample code -

%%
16(divisible by 4) {printf("divisible by 4 %s\n",yytext);}
%%
main()
{
        yylex();
}

Solution

  • %%  
    [0-9]+  {int number = atoi(yytext); if((number % 4) == 0) printf("Div_4 %d\n", number);}
    %%
    
    main()
    {
            yylex();
    }
    

    As lex/flex support C, so you can save the string as integer and then check it in C.