我希望 flex 词法分析器对
q
标记有一个特例,因为只有当它是一行中除空格之外的唯一内容时,它才会被识别。给定:
S [ \f\r\t\v]
%%
^{S}*q{S}*$ { exit(0); }
这确实不匹配
q
。如果我删除尾随的$
,那么它匹配;但随后它也匹配像 q foo
这样的东西,即 q
not 单独在一条线上。
为什么
$
不起作用?我怎样才能得到我想要的?
仅供参考:
$ flex --version
flex 2.6.4 Apple(flex-34)
我无法重现你的问题(它“对我有用”)——但证明这一观察的合理性所需的信息比评论中的要多。
使用您的代码变体:
%option noinput
%option nounput
%option noyywrap
S [ \f\r\t\v]
%%
^{S}*q{S}*$ { printf("Quit!\n"); exit(0); }
%%
int main(void)
{
yylex();
return 0;
}
使用 Flex 2.6.4 Apple(flex-34) 在 macOS Monterey 12.6.3 上编译,我得到如下输出:
$ flex61
Absolute
Absolute
Aquaduct
Aquaduct
Q !
Q !
q !
q !
q
Quit!
$
这看起来像您正在寻找的行为。 “
q
on its own”行末尾有尾随空白,但仅包含 q
的行也会终止程序并显示 Quit!
消息。我用命令编译它:
flex flex61.l
clang -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes \
-fno-common -Wno-sign-compare -Wno-nullability-completeness -o flex61 lex.yy.c
需要
-Wno-nullability-completeness
来抑制<stdio.h>
的大量令人讨厌的警告; -Wno-sign-compare
避免了生成的 C 代码中的一个问题。
$ clang --version
Apple clang version 14.0.0 (clang-1400.0.29.202)
Target: x86_64-apple-darwin21.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
$
故障的可能原因:
before the
exit(0);` 以证明您正在编辑的代码是正在编译和执行的代码。