在flex/lex中难以获得C样式的注释 [英] difficulty getting c-style comments in flex/lex

查看:49
本文介绍了在flex/lex中难以获得C样式的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在flex中制定一条规则,以使用像/* */

I want to make a rule in flex to consume a c-style comment like /* */

我有以下

c_comment "/*"[\n.]*"*/"

但是从来没有匹配过.知道为什么吗?如果您需要更多我的代码,请告诉我,我将提交整个内容.感谢任何答复.

But it doesn't ever get matched. Any idea why? if you need more of my code please let me know and I'll submit the whole thing. Thanks to anyone who replies.

推荐答案

我建议您使用

请注意,<condition>和规则之间必须一定.

Do note that there must not be any whitespace between the <condition> and the rule.

%x C_COMMENT定义C_COMMENT状态,并且规则/*启动它.一旦启动,*/将使其返回初始状态(INITIAL是预定义的),并且所有其他字符将被消耗而无需任何特殊操作.当两个规则匹配时,Flex会采用最长匹配的规则来消除歧义,因此点规则不会阻止*/匹配. \n规则是必要的,因为一个点匹配除换行符之外的所有内容.

%x C_COMMENT defines the C_COMMENT state, and the rule /* has it start. Once it's started, */ will have it go back to the initial state (INITIAL is predefined), and every other characters will just be consumed without any particular action. When two rules match, Flex disambiguates by taking the one that has the longest match, so the dot rule does not prevent */ from matching. The \n rule is necessary because a dot matches everything except a newline.

%x定义使C_COMMENT成为独占状态,这意味着词法分析器仅会在进入状态后匹配带有标记" <C_COMMENT>的规则.

The %x definition makes C_COMMENT an exclusive state, which means the lexer will only match rules that are "tagged" <C_COMMENT> once it enters the state.

这是一个微型示例词法分析器,它通过打印除.

Here is a tiny example lexer that implements this answer by printing everything except what's inside /* comments */.

这篇关于在flex/lex中难以获得C样式的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆