2014-10-17 112 views
1

我想在LEX中編寫一個程序,刪除輸入中的評論。註釋可以寫在以下方面:刪除評論的程序

  • /*comment*/
  • //comment
  • /*comment /*comment*/ */

我的想法是: 認識一些方式,如果輸入與/*開始 - >然後我會找/*並忽略裏面的文本。如果輸入從//開始,我會忽略它直到行尾。

但我不知道如何實現這一點。

回答

1

單獨使用Lex模式無法處理嵌套註釋,因此您需要處理使用Lex狀態嵌套的遞歸性質(或者編寫遞歸下降解析器)。

使用lex,使用狀態的堆棧管理例程(yy_push_state()yy_pop_state()yy_top_state()

簡單的例子:

%x BLOCKCOMMENT 

"/*"     { yy_push_state(BLOCKCOMMENT); } 
<BLOCKCOMMENT>"*/" { if(yy_top_state() == BLOCKCOMMENT) 
          yy_pop_state(); 
         else 
          fprintf(stderr, 
          "Error: comment close `*/` found while not in comment\n"); 
        } 
<BLOCKCOMMENT>.  { /* consume */ } 

.     { return yytext[0]; }