最近,我使用flex来做一些词法分析工作,我在flex中是全新的。考虑以下情况,我有一个多行注释来进行模式匹配,
/**
*
* multiline comment
*
*/
在flex中,正则表达式:
\/\*.*\*\/
与此多行注释不匹配,但只匹配单行评论,如:
/** single comment **/
所以,看起来flex的模式匹配就像grep那样是“单行模式”,我是对的吗?
答案 0 :(得分:0)
答案 1 :(得分:0)
匹配多行C / C ++注释的一个正确的Flex模式是:(取自this answer)
[/][*][^*]*[*]+([^*/][^*]*[*]+)*[/]
Flex不提供非贪婪的重复运算符,因此上面是最简单的正则表达式,它在第一次结束*/
时停止。或者,您可以使用开始条件(改编自Flex manual):
%x comment
%%
"/*" BEGIN(comment);
<comment>[^*]* /* eat anything that's not a '*' */
<comment>"*"+"/" BEGIN(INITIAL);
<comment>"*"+ /* eat up '*'s not followed by a '/' */
<comment><<EOF>> { yyerror("Unterminated comment");
return 0;
}
答案 2 :(得分:-1)
.
匹配除换行符之外的任何字符,因此请使用(.|\n)*
。以你的例子:
\/\*(.|\n)*\*\/