Lex: C keyword rules that are not defined correctly

I wrote a simple lex file to define C keywords. My rules look like this:

keyword do|while|char|if
%%
{keyword}  { printf("Keyword %s found.", yytext); }

A problem in a rule correctly identifies charin the source code, but also identifies things putcharlike the keyword char. How can I make a rule identify a keyword char, and not when it is present in other words?

+4
source share
2 answers

You need to put keywords before identifiers. All this. Lex sequentially searches for regular expressions.

%%

IF|ELSE|etc {action for keywords }

[a-zA-Z_][a-zA-Z0-9]* {action for identifiers}

%%
+2
source

( , "put" ), - .

lexer, , , .

0

Source: https://habr.com/ru/post/1625088/


All Articles