c - 检测 Flex 中的注释

标签 c flex-lexer

我刚刚学习flex。我编写了一个简单的程序来检查给定文本文件中的单词是否为动词并打印它们。我想检测输入文件中是否有任何单行或多行注释(如 c 和 c++ 样式注释)并打印整个注释以输出。有没有办法做到这一点?我的示例代码如下:

%%

[\t]+

is   |

am   |

are  |

was  |

were {printf("%s: is a verb",yytext);}

[a-zA-Z]+ {printf("%s: is a verb",yytext);}

. |\n

%%

int main(int argc, char *argv[]){    
    yyin = fopen(argv[1], "r");    
    yylex();         
    fclose(yyin);
}

最佳答案

情况有点复杂。我建议使用start conditions用于处理评论。这是我为此快速组合的一个词法分析器:

%option noyywrap
%x COMMENT_SINGLE
%x COMMENT_MULTI

%top{
/* for strndup */
#include <string.h>
}

%{
char* commentStart;
%}

%%

[\n\t\r ]+ { 
  /* ignore whitespace */ }

<INITIAL>"//" { 
  /* begin of single-line comment */ 
  commentStart = yytext; 
  BEGIN(COMMENT_SINGLE); 
}

<COMMENT_SINGLE>\n { 
  /* end of single-line comment */
  char* comment = strndup(commentStart, yytext - commentStart);
  printf("'%s': was a single-line comment\n", comment);
  free(comment); 
  BEGIN(INITIAL); 
}

<COMMENT_SINGLE>[^\n]+ { 
  /* suppress whatever is in the comment */
}

<INITIAL>"/*" { 
  /* begin of multi-line comment */
  commentStart = yytext; 
  BEGIN(COMMENT_MULTI); 
}

<COMMENT_MULTI>"*/" { 
  /* end of multi-line comment */
  char* comment = strndup(commentStart, yytext + 2 - commentStart);
  printf("'%s': was a multi-line comment\n", comment);
  free(comment); 
  BEGIN(INITIAL); 
}

<COMMENT_MULTI>. { 
  /* suppress whatever is in the comment */
} 

<COMMENT_MULTI>\n { 
  /* don't print newlines */
} 

is   |
am   |
are  |
was  |
were { 
  printf("'%s': is a verb\n", yytext); 
}

[a-zA-Z]+ { 
  printf("'%s': is not a verb\n", yytext); 
}

. { 
  /* don't print everything else */ 
}

%%

int main(int argc, char *argv[]){    
  yyin = fopen(argv[1], "r");    
  yylex();         
  fclose(yyin);
}

注意:词法分析器代码已经足够长,因此我省略了任何错误检查。

关于c - 检测 Flex 中的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29706000/

相关文章:

C: 为 hexdump 格式化字符串(char* 到另一个 char*)

C - execlp 函数调用 - 我可以让 argv 指向更多参数吗

C链表循环引用

c - 如何使用 flex/bison 解析 C 字符串 (char *)?

parsing - 开发一个简单的解析器

grammar - Flex 和 Bison 的使用

regex - Flex 正则表达式文字 char

c - 在C编程中处理客户端-服务器套接字中的ctrl+c

c - linux附加文件

连接两个捕获组