Flex / Bison - 开始状态

时间:2012-05-04 15:19:04

标签: bison flex-lexer

您有以下代码

%s expectWord

%%

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

代码应该检查用户是否输入“和”,如果他们输入了“if”,那么如果用户输入多个和之后,它们将被忽略,最后有一个单词将返回该单词。 因此,如果用户输入:a和and和and和b,lexer应该返回:a和b。所以只有一个并将被退回。

现在,它正在回归:a b。 我该如何修复此代码?

由于

1 个答案:

答案 0 :(得分:2)

这是实现目标的一种方法:

%{
#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();
}

并测试它我们得到:

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'