Delete Nested Comments BZ Lex

How to program in lex (or flex) to remove nested comments from the text and print only the text that is not in the comments?
I should somehow identify my state when I am commenting and the number of “tags” in the block comment.

Let us have rules:
Block comments

p>

/*
block comment
*/

Line comment

/ / line comment

3. Comments can be nested.

Example 1

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

Output:

show show

Example 2

show /* // comment
comment
*/
show

Output:

show 
show

Example 3

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

Output:

show
show

Your theory is correct. This is a simple Implementation; can be improved.

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

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

/* Could have been .| ECHO, but this is more efficient. */
([^/]* ([/][^/*])*)* ECHO;
%%

How to program in lex (or flex) to delete from text Nest comments and print only the text that is not in the comments?
I should somehow identify my state when I am commenting and the number of “tags” in the block comment.

Let us have rules:
Block comments

p>

/*
block comment
*/

Line comment

/ / line comment

3. Comments can be nested.

Example 1

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

Output:

show show

Example 2

show /* // comment
comment
*/
show

Output:

show 
show

Example 3

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

Output:

show
show

Your theory is correct. This is a simple implementation; it can be improved.

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

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

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

/* Could have been .| ECHO, but this is more efficient. */
([^/]*([/][^/*])*)* ECHO;
%%

< p>

Leave a Comment

Your email address will not be published.