简体   繁体   English

Flex(词法分析器){+}和{-}运算符

[英]Flex (lexical analyzer) {+} and {-} operators

I am trying to make a simple scanner using Flex. 我正在尝试使用Flex制作一个简单的扫描仪。 In the declarations section, I am trying to use the {-} operator to exclude reserved words from an id, but I can't get it to work. 在声明部分,我试图使用{-}运算符从ID中排除保留字,但无法使其正常工作。 Every example I have found uses the {+} and {-} operators as in the following code: 我发现的每个示例都使用{+}和{-}运算符,如以下代码所示:

    [a-z]{-}[d]

However, I am trying to use these operators as in the following code, but I always get errors: 但是,我试图像下面的代码一样使用这些运算符,但是我总是会出错:

    invalid_id   "char"|"else"|"if"|"class"|"new"|"return"|"void"|"while"|"int"
    all_ids      [a-zA-Z_][a-zA-Z0-9_]*
    id           {all_ids}{-}{invalid_id}

Is there any way to make it work? 有什么办法可以使其工作? Can these operators be used without square brackets? 这些运算符可以不带方括号使用吗?

The {-} and {+} operators only work on character classes like [az] , not on full regular expressions or strings. {-}{+}运算符仅适用于像[az]这样的字符类,不适用于完整的正则表达式或字符串。 flex does not have support for a more general {-} operator. flex不支持更通用的{-}运算符。 The more general version of {+} of course is | 当然,更一般的{+}版本是| . Your particular problem is in general solved by the fact that if two patterns match the same string, then the first pattern will be used. 通常,如果两个模式匹配相同的字符串,则将使用第一个模式,从而解决了您的特定问题。 So changing your specification to the following will actually exclude all keywords from the ID s. 因此,将您的规范更改为以下内容实际上将排除ID的所有关键字。

%%
"char"|"else"|"if"|"class"|"new"|"return"|"void"|"while"|"int"  { return KEYWORD; }
[a-zA-Z_][a-zA-Z0-9_]*   { return ID; }
%%

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM