5

テキストからネストされたコメントを削除し、コメントに含まれていないテキストだけを出力するには、lex (または flex) でどのようにプログラムすればよいですか? コメント中の状態と、ブロックコメントの開始「タグ」の数を何らかの形で認識できるはずです。

ルールを作りましょう:
1.ブロックコメント

/*
block comment
*/

2.ラインコメント

// line comment

3. コメントは入れ子にすることができます。

例 1

show /* comment /* comment */ comment */ show

出力:

show  show

例 2

show /* // comment
comment
*/
show

出力:

show 
show 

例 3

show
///* comment
comment
// /*
comment
//*/ comment
//
comment */
show

出力:

show
show
4

3 に答える 3

7

あなたは理論を正しく理解しました。簡単な実装を次に示します。改善することができます。

%x COMMENT
%%
%{
   int comment_nesting = 0;
%}

"/*"            BEGIN(COMMENT); ++comment_nesting;
"//".*          /* // comments to end of line */

<COMMENT>[^*/]* /* Eat non-comment delimiters */
<COMMENT>"/*"   ++comment_nesting;
<COMMENT>"*/"   if (--comment_nesting == 0) BEGIN(INITIAL);
<COMMENT>[*/]   /* Eat a / or * if it doesn't match comment sequence */

  /* Could have been .|\n ECHO, but this is more efficient. */
([^/]*([/][^/*])*)* ECHO;  
%%
于 2012-10-18T07:34:45.547 に答える
2

これはまさにあなたが必要とするものです:yy_push_state(COMMENT)それはネストされた状況で便利な私たちの状態を保存するためにスタックを使用します。

于 2013-03-09T16:59:56.077 に答える
0

@rici の答えが間違っているのではないかと心配しています。最初に行番号を記録する必要があり、後でファイルディレクティブを変更する可能性があります。2 番目に open_sign と close_sign を指定します。以下の原則があります。

1) using an integer for stack control: push for open sign, popup for close sign
2) eat up CHARACTER BEFORE EOF and close sign WITHOUT open sign inside
<comments>{open} {no_open_sign++;}
<comments>\n {curr_lineno++;}
<comments>[^({close})({open})(EOF)] /*EAT characters by doing nothing*/
3) Errors might happen when no_open_sign down to zero, hence
<comments>{close}  similar as above post
4) EOF should not be inside the string, hence you need a rule
<comments>(EOF) {return ERROR_TOKEN;}

より堅牢にするために、外側に別の綿密なチェックルールも必要です

そして実際には、字句解析器がサポートしている場合は、正規表現文法の前に否定形を使用し、後ろ向きにする必要があります。

于 2016-10-06T05:41:34.277 に答える