带有C的词法分析器,新行令牌

时间:2012-11-25 14:28:01

标签: lexical-analysis lexical

我有4条规则

rule1: match variable 
rule2: match Float 
rule3: match Integer 
rule4: [ \t] ; //skipping space, tabs 
rule5: \n ;

现在我想要一个匹配错误的规则,其他任何不是ID,Float,Integer的规则,例如:“& ^()>〜....”

所以这就是我创建的规则:

. {   printf("found an error:%s\n",yytext);
      err_count++;
}

但是有一些问题,只要扫描仪跳到下一行,它就会捕获一个未知的令牌。

我的意见:

12+32+22:18,18
99558^8*6
15.~646(5
My output

    Found a number:12
    Found a error:+
    Found a number:32
    Found a error:+
    Found a number:22
    Found a error::
    Found a number:18
    Found a error:,
    Found a number:18
    Found a error:
    Found a number:99558
    Found a error:^
    Found a number:8
    Found a error:*
    Found a number:6
    Found a error:
    Found a float:15.
    Found a error:~
    Found a number:646
    Found a error:(
    Found a number:5

出于调试目的,我尝试通过用方括号

将其括起来找出令牌
. {
        printf("Found a error:[%s]\n",yytext);
        err_count++;
        }

bash show:
    Found a number:12
    Found a error:[+]
    Found a number:32
    Found a error:[+]
    Found a number:22
    Found a error:[:]
    Found a number:18
    Found a error:[,]
    Found a number:18
    ]ound a error:[
    Found a number:99558
    Found a error:[^]
    Found a number:8
    Found a error:[*]
    Found a number:6
    ]ound a error:[
    Found a float:15.
    Found a error:[~]
    Found a number:646
    Found a error:[(]
    Found a number:5

 redirect output to a txt file
    Found a number:12
    Found a error:[+]
    Found a number:32
    Found a error:[+]
    Found a number:22
    Found a error:[:]
    Found a number:18
    Found a error:[,]
    Found a number:18
    Found a error:[
    ]
    Found a number:99558
    Found a error:[^]
    Found a number:8
    Found a error:[*]
    Found a number:6
    Found a error:[
    ]
    Found a float:15.
    Found a error:[~]
    Found a number:646
    Found a error:[(]
    Found a number:5

有谁知道导致问题的原因是什么?谢谢 我可以向你保证规则5:\ n;工作正常,这是证据

I add print to rule5"\n { printf("newline\n"); 

redirect output to a txt file
Found a number:12
Found a error:[+]
Found a number:32
Found a error:[+]
Found a number:22
Found a error:[:]
Found a number:18
Found a error:[,]
Found a number:18
Found a error:[
]
newline
Found a number:99558
Found a error:[^]
Found a number:8
Found a error:[*]
Found a number:6
Found a error:[
]
newline
Found a float:15.
Found a error:[~]
Found a number:646
Found a error:[(]
Found a number:5
Found a error:[
]
newline
Found a variable:T189_10
Found a error:[@]
Found a float:12.2
Found a error:[
]
newline
Found a number:1
Found a variable:ABB21u
Found a error:[=]
Found a variable:ier_
Found a error:[
]
newline
Found a error:[$]
Found a error:[%]
Found a error:[^]

1 个答案:

答案 0 :(得分:2)

你必须查找回车符(\ r),按下返回按钮时,Windows系统插入两个字符是常见的,两个字符是新行(\ n)和回车符(\ r \ n) ),以这种方式添加:

rule4: [ \t\r]

它会正常工作。