You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lex规则可正确验证赋值语句但无法验证合法表达式的问题求助

Lex规则可正确验证赋值语句但无法验证合法表达式的问题求助

大家好,我最近翻出了之前没搞定的一个作业,一直好奇问题到底出在哪。这个作业要求用C结合Lex写正则表达式,用来验证两种输入:表达式和赋值语句。现在赋值语句能被正确判定为合法,但所有的表达式都被Lex判定为无效输入。我对着代码抠了好久还是没找到问题所在,有没有大佬能帮忙分析下?

我的Lex代码(a3.l)

/*regular definitions*/
id [a-zA-Z]+[a-zA-Z0-9]*[ \t]
op [-|+|"*"|"/"|%][ \t]
equ [=][ \t]
expr {id}{op}{id}({op}{id})*\n
assmt {id}{equ}({id}{op}{id}({op}{id})*)[;]\n

%%
[\n] printf("\nInvalid input\n");
{expr} printf("%sLegal expression \n", yytext);
{assmt} printf("%sLegal assignment \n", yytext);

编译和测试步骤

我是按照下面的命令编译和测试的:

lex a3.l  # 生成lex.yy.c文件
gcc lex.yy.c -lfl -o a3  # 编译为可执行程序a3
./a3 < in.txt > out.txt  # 读取in.txt的输入,将验证结果输出到out.txt

测试输入文件(in.txt)

good = one1 + two2 - three3 / four4 ;
good = one1 / two2 * three3 ;
good = one1 * two2 + three3 ;
good = ONE + twenty - three3 ;
good = old * thirty2 / b567 ;
good * i8766e98e + bignum
good % a4 + bignum
good * one - two2 / three3
bad = = one1 + two2 - three3 / four4 ;
bad = one + two2 - three3 / four4
bad = one + - two2 - three3 / four4 ;
bad = one + two2 ? three3 / four4 ;
bad = 4 + ( one1 * two2 ) * ( three3 + four4 ;
bad = one1 + 24 - three3 ;
bad +- delta
bad / min = fourth ;
bad = a + b
bad = a ! b
bad = 2two + 3three ;
bad * 2two + 3three
good + two
bad + notgood ;

实际输出结果(out.txt)

good = one1 + two2 - three3 / four4 ; Legal assignment 
good = one1 / two2 * three3 ; Legal assignment 
good = one1 * two2 + three3 ; Legal assignment 
good = ONE + twenty - three3 ; Legal assignment 
good = old * thirty2 / b567 ; Legal assignment 
good * i8766e98e + bignum 
Invalid input
good % a4 + bignum 
Invalid input
good * one - two2 / three3 
Invalid input
bad = = one1 + two2 - three3 / four4 ; 
Invalid input
bad = one + two2 - three3 / four4 
Invalid input
bad = one + - two2 - three3 / four4 ; 
Invalid input
bad = one1 + two2 ? three3 / four4 ; 
Invalid input
bad = 4 + ( one1 * two2 ) * ( three3 + four4 ; 
Invalid input
bad = one1 + 24 - three3 ; 
Invalid input
bad +- delta 
Invalid input
bad / min = fourth ; 
Invalid input
bad = a + b 
Invalid input
bad = a ! b 
Invalid input
bad = 2two + 3three ; 
Invalid input
bad * 2two + 3three 
Invalid input
good + two 
Invalid input
bad + notgood ; 
Invalid input

具体问题

可以看到,像good * i8766e98e + bignum、good % a4 + bignum这些应该是合法的表达式,都被判定为“Invalid input”,但赋值语句都能被正确识别。我实在找不到正则表达式哪里写错了,希望有人能帮我指出问题所在,谢谢大家!


内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 11:53:08