How to find all word except a few in flex?

▼魔方 西西 提交于 2019-12-11 04:47:16

问题


I need to find all words except a few (e.g. "car", "bus", "train") in flex. Have you got any ideas how to do it?


回答1:


This has been left unanswered for some time, and is a standard problem that new users of lex/flex encounter when starting. There is also not a clear answer elsewhere on SO.

The question is asking how do you match all identifiers that are not reserved words. This is a standard computer language feature that occurs in almost every compiler. It just was not expressed in a way that made that clear. In compiler construction, using flex, we have to find all words (also known as identifiers) except a few (e.g. "if", "then", "else"). This is achieved by the order in which the lexical patterns are put in the specification. It is so common that the main example in the Wikipedia page on Flex shows this!

We would do it this way:

car    return(CAR);
bus    return(BUS);
train    return(TRAIN);
[a-z]+   return(WORD);

However, if we did this in a different order we would get an error:

[a-z]+   return(WORD);
car    return(CAR);
bus    return(BUS);
train    return(TRAIN);

It would object to the matching of "car", "bus" and "train" as they are already included in WORD.

This situation also occurs elsewhere in languages. Take for example the symbols "=", ">=", ">", "==", "++", "+", "+=" etc. We also have to be careful which order we define their lexemes in flex to ensure no errors.



来源:https://stackoverflow.com/questions/13670165/how-to-find-all-word-except-a-few-in-flex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!