Detecting and skipping line comments with Flex

前端 未结 3 1798
自闭症患者
自闭症患者 2020-12-10 19:51

How can I detect one line comments like // in Flex and skip those lines?

Also, for /* comments, will the following snippet be enough?

3条回答
  •  [愿得一人]
    2020-12-10 20:30

    To detect single line comments :

    ^"//"    printf("This is a comment line\n");
    

    This says any line which starts with // will be considered as comment line.

    To detect multi line comments :

    ^"/*"[^*]*|[*]*"*/" printf("This is a Multiline Comment\n");
    

    *

    Explanation :

    *

    ^"/*" This says beginning should be /*.

    [^*]* includes all characters including \n but excludes *.

    [*]* says 0 or more number of stars.

    [^*]|[*]* - "or" operator is applied to get any string.

    "*/" specifies */ as end.

    This will work perfectly in lex.

    Below is the complete code of lex file :

    %{
    #include 
    int v=0;
    %}
    %%
    ^"//"    printf("This is a comment line\n");
    ^"/*"[^*]*|[*]*"*/" printf("This is a Multiline Comment\n");
    .|\n {}
    %%
    int yywrap()
    {
        return 1;
    }
    main()
    {
        yylex();
    }
    

提交回复
热议问题