regex - 语法分析器如何忽略输入中的空格

标签 regex flex-lexer lexical-analysis

在下面的代码中,虽然我添加了 \t 作为 token ,其优先级高于数字,但当我测试它时,它仍然接受 -2- 2 (在 - 之后有一个空格)和 -2 - 2 (在 - 周围有 2 个空格),但它不接受-2-2(没有空格)。对于这种特殊情况有解决方案吗?

我的目标是,当我给它输入诸如 -2-2-22*3/6-1 时,它工作正常并且不输出“语法错误”。

词法.l

/* recognize tokens for the calculator and print them out */
/*"--"[0-9]+ { yytext++; yylval = atoi(yytext); return NUMBER; }*/
%{
#include"syntax.tab.h"

%}

%%
"+"    { return ADD; }
"-"    { return SUB; }
"*"    { return MUL; }
"/"    { return DIV; }
"|"    { return ABS; }
[ \t]  { /* ignore whitespace */ }
(-|"")[0-9]+  { yylval = atoi(yytext); return NUMBER; }
\n     { return EOL; }

.      { printf("Mystery character %c\n", *yytext); }
%%

syntax.y

/* simplest version of calculator */
%{
#include <stdio.h>
%}

/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL

%%

calclist: /* nothing */                       
 | calclist exp EOL { printf("= %d\n", $2); }
 ;

exp: factor       
 | exp ADD factor { $$ = $1 + $3; }
 | exp SUB factor { $$ = $1 - $3; }
 ;

factor: term        
 | factor MUL term { $$ = $1 * $3; }
 | factor DIV term { $$ = $1 / $3; }
 ;

term: NUMBER   
 | ABS term   { if ($2 < 0) $$ = -$2; else $$ = $2; }
;
%%
main(int argc, char **argv)
{
  yyparse();
}

yyerror(char *s)
{
  fprintf(stderr, "error: %s\n", s);
}`

最佳答案

-2-2 被词法分析器解释为 -2 -2,而不是 -2 - 2 。 Lexer 总是寻找最长的匹配,因此它总是更喜欢将减号和数字视为单个标记。

您的解析器没有接受两个连续数字的规则,因此会显示错误。 (您应该学习在词法分析器和解析器中打开调试输出。在这种情况下这非常有帮助。)

要解决此问题,您需要在词法分析器中删除作为数字一部分的 -。 将其合并到数字中是非常常见的错误,它会导致您遇到的此类问题。 相反,您可以在解析器中定义一元 - 运算符。

(顺便说一句,(-|"") 可以写成 -?。)

关于regex - 语法分析器如何忽略输入中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76030057/

相关文章:

mysql - 如何从 MySQL 列内的 img 标签中删除宽度和高度?

c - parser.y :79. 33-41 : symbol character is used, 但未定义为 token 且没有规则

mysql - 如何从数据库列中分解用户 ID?

javascript - 在 Javascript 中查找 URL 中的基本名称

regex - 从 Rails 3 中的 JSON 响应中剥离数字?

c - 尝试编程 "include"功能时在 flex/bison 程序中调试断言失败错误

grammar - Flex,多行规则

c++ - 在 windows 上制作 flex.exe

algorithm - 如何以编程方式检测 CV 中的漏洞/个人信息(通过语法分析/解析等...)

c - 如何向 C 词法分析器添加浮点解析功能?