How can I detect one line comments like //
in Flex and skip those lines?
Also, for /*
comments, will the following snippet be enough?
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();
}