Search code examples
c++g++flex-lexer

flex parse symbol - complex symbol


I'm new to flex, I'm just trying to parse a number :

%{
  #include <iostream>
  using namespace std;
  extern int yylex();
%}
%option noyywrap

DIGIT    [0-9]
ID       [a-z][a-z0-9]*
NUM      {DIGIT}*"."{DIGIT}* | {DIGIT}+

%%
{NUM}   {printf("Number encountered : %s\n",yytext);}
%%
int main(int, char**) {
  while (yylex());
}

When I replace the Number encountered line with

{DIGIT}+    { printf( "Number %s\n", yytext);}
{DIGIT}*"."{DIGIT}*       { printf( "Number %s\n", yytext);}

I get output, but now I don't.

I mean it doesn't parse correctly. It prints out nothing.

How can solve this problem?

Current code :

%{
  #include <iostream>
  using namespace std;
  extern int yylex();
%}
%option noyywrap

WS  [ \t\n]+
DIGIT    [0-9]
NUM      ({DIGIT}*"."{DIGIT}*|{DIGIT}+)
%%
NUM {printf("num : %s\n",yytext);}
%%

Solution

  • Simple just do this :

    NUMBER  {N}+|{N}+"."{N}+|"."{N}+|{N}+"."