Flex Help
Flex Help
While it might be found in some libc’s, you might also have to link
explicitly with -lfl.
The lexer function is called yylex(), and it is quite easy to interface
with bison/yacc.
{ definitions }
%%
{ rules }
%%
{ user subroutines }
Definitions
regularexpression action
s literal string s
\c character c literally
^ beginning of line
s* zero or occurrences of s
r|s r or s
{s} grouping
$ end of line
rs|tu rs or tu
name definition
The name is just a word beginning with a letter (or underscore, but
I don’t recommend those) followed by zero or more letters,
underscores, or dashes. The definition actually from the first
non-whitespace character to the end of line. You can refer to it via
{name}, which will expand to your definition.
Flex definitions
For example:
DIGIT [0-9]
{DIGIT}*\.{DIGIT}+
is equivalent to
([0-9])*\.([0-9])+
Flex example
%{ int num_lines = 0;
int num_chars = 0;
%}
%%
\n {++num_lines; ++num_chars;}
. {++num_chars;}
%%
int main(int argc, char **argv)
{
yylex();
printf("# of lines = %d, # of chars = %d\n",
num_lines, num_chars);
}
code
Another example
digits [0-9]
ltr [a-zA-Z]
alphanum [a-zA-Z0-9]
%%
(-|\+)*{digits}+ printf("found number: ’%s’\n",yytext)
{ltr}(_|{alphanum})* printf("found identifier: ’%s’\n",yyt
\. printf("found character: {%s}\n",yyte
. { /* ignore others */ }
%%
int main(int argc, char **argv)
{
yylex();
}
code