sap
sap

Reputation: 1141

Flex/Bison - start condition

Hi have the following code

%s expectWord

%%

<expectWord>"and"+{word}   { BEGIN( INITIAL );}
<expectWord>["and"]*       { /* Skip */;}
"and"                      { BEGIN( expectWordAfterAND ); return AND; }

The code is supposed to check if user entered "and" and if they did then if user enters multiple ands after that, they will be ignored and when finally there is a word that word will be returned. So if user enters: a and and and and and and b, lexer should return: a and b. so Only one and will be returned.

Right now, it's returning: a b. how do I fix this code?

Thanks

Upvotes: 0

Views: 2549

Answers (1)

Arlen
Arlen

Reputation: 6835

Here is one way to achieve what you want:

%{
#include <iostream>
using namespace std;
#define YY_DECL extern "C" int yylex()
%}

WORD [:alnum:]+
%x SPACE
%x AND

%%

WORD ECHO;
^[ ]*and[ ] BEGIN(AND);
[ ]* { cout << " "; BEGIN(SPACE); }

<SPACE>{
and[ ] ECHO; BEGIN(AND);
.|\n ECHO; BEGIN(INITIAL);
}

<AND>{
and$
([ ]*and[ ])*
.|\n ECHO; BEGIN(INITIAL);

}

%%

main()
{
    // lex through the input:
    yylex();
}

and testing it we get:

input> 'a and and b'
output> 'a and b'
input> 'a and and and b'
output> 'a and b'
input> 'a b and and c'
output> 'a b and c'
input> 'and and b c and a'
output> 'b c and a'

Upvotes: 2

Related Questions