【发布时间】:2021-12-04 17:44:11
【问题描述】:
我正在使用 JFlex 编写一个词法分析器。当单词co 匹配时,我们必须忽略后面的内容,直到行尾(因为它是注释)。目前,我有一个布尔变量,只要匹配这个词,它就会更改为true,并且如果在co 之后匹配标识符或运算符直到行尾,我只是忽略它,因为我有一个@987654324我的Identifier 和Operator 令牌标识中的@ 条件。
我想知道是否有更好的方法来做到这一点并摆脱这个无处不在的if 声明?
代码如下:
%% // Options of the scanner
%class Lexer
%unicode
%line
%column
%standalone
%{
private boolean isCommentOpen = false;
private void toggleIsCommentOpen() {
this.isCommentOpen = ! this.isCommentOpen;
}
private boolean getIsCommentOpen() {
return this.isCommentOpen;
}
%}
Operators = [\+\-]
Identifier = [A-Z]*
EndOfLine = \r|\n|\r\n
%%
{Operators} {
if (! getIsBlockCommentOpen() && ! getIsCommentOpen()) {
// Do Code
}
}
{Identifier} {
if (! getIsBlockCommentOpen() && ! getIsCommentOpen()) {
// Do Code
}
}
"co" {
toggleIsCommentOpen();
}
. {}
{EndOfLine} {
if (getIsCommentOpen()) {
toggleIsCommentOpen();
}
}
【问题讨论】:
-
为什么不将
co中的单个评论匹配到行尾?
标签: flex-lexer lexer jflex