2017-02-28 22 views
0

我正在設計一個接受簡單c代碼的lex,其中我想要一個接受多個分號的規則。我試過(; {2,})&(;; +)但它不接受。如何驗證int i ;;;在lex?

語句法是去工作的是

int i=1; 
i=3*2;;;; 

而且我想補充的正則表達式,從而允許其報表。因爲C驗證;;;;。

+1

您提供的2種模式至少需要2個分號。這是你的意圖嗎?也許你想嘗試'; +'? –

+0

實際上,我想要做的只是允許單個分號,並消除字符串中的所有其他字符,如C編譯器句柄;;;;;; –

+1

在您的解析器中執行此操作,而不是您的詞法分析器。你的解析器應該只是記錄一個空的語句。 – rici

回答

0

我無法重現OP。這是我的嘗試:

文件test-semicolon.l

%{ 
#include <stdio.h> 
%} 

%option noyywrap 

%% 

;{2,} printf("HERE->%s", yytext); 
. ECHO; 

%% 

int main(int argc, char **argv) { yylex(); return 0; } 

編譯和flex和海灣合作委員會在Cygwin上測試:

$ flex -V 
flex 2.6.3 

$ flex -otest-semicolon.c test-semicolon.l ; gcc -o test-semicolon test-semicolon.c 
test-semicolon.c:398:0: warning: "yywrap" redefined 

^ 
test-semicolon.c:74:0: note: this is the location of the previous definition 

^ 

$ echo ' 
> 123 
> 123; 
> 123;; 
> 123;;; 
> 123;;;; 
> int i=1; 
> i=3*2;;;; 
> ' | ./test-semicolon 

123 
123; 
123HERE->;; 
123HERE->;;; 
123HERE->;;;; 
int i=1; 
i=3*2HERE->;;;; 

$ 

輸出顯示的兩個或兩個以上;任何序列匹配如預期。

Btw。,lex和yacc來源爲C可在ANSI C grammar, Lex specificationANSI C Yacc grammar

另外,我可以推薦這本書:A Retargetable C Compiler: Design and Implementation

相關問題