Lex is a UNIX tool, so we need to use flex instead so that it can be used in windows;
Pairing:
Lex and YACC
Flex and bison
Jflex and javacup
Lex is a lexical analyzer and mainly serves as a scanner. The input is the source code (of course, the example we write is not necessarily the source code), and the output is a lexical unit (generalized, such as 1, 2, 3 can be called Num );
Of course, the process of intermediate matching is very complicated, such as matching Regular Expressions and outputting; you do not need to consider this when using lex. We only need to define the following points:
(1)Regular ExpressionFor example, if integer is an integer in the language we define, the input is an integer that matches the regular expression;
(2)Returned lexical UnitYou need to define what to return when matching;
: Http://download.csdn.net/detail/loseblue/283175#comment
Ii. files downloaded using LEX: for example, we write a statistical statement for the number of text words, number of white spaces, and number of numbers. Step 1: Define the *. l file.
Define a *. l file at the beginning. The template is explained as follows:
% {// Declare some variables or functions %} // define regular expressions // For example: // num ([0-9]) + // The symbol on the left, on the right side, the regular expression % // defines a series of actions. That is, if the action matches the action after a regular expression defined above, this action is a C language statement // For example: // {num} {printf ("num") ;}// {mode} on the left and {C statement} on the right; % void main () // execute the main function {yylex (); // start the parsing statement, built-in function // define the C language statement} int yywrap () {return 1 ;}
The actual code is as follows:
% {Int wordcount = 0; int whitecount = 0; int numcount = 0; %} letter [A-Za-Z] letters {letter} + numbers ([0-9]) + whitespaces ([\ t \ n]) + % {letters} {wordcount ++;} // The action executed when matching the Regular Expression of letters, the general action is to combine YACC and return a lexical unit and attribute value to the syntax analyzer. Here, Lex is used as an independent tool {numbers} {numcount ++ ;} {whitespaces} {whitecount ++ ;}% void main () {yylex (); // starts the parsing statement. The built-in function printf ("Number of words: % d \ n ", wordcount); printf ("white space: % d \ n", whitecount); printf ("number: % d \ n", numcount);} int yywrap () {return 1 ;}
Step 2: Use the flex command
Enter the command: Flex 1.l
Note: The command line opened by lexyacc. bat is used here;
Flex 1.l generates Lex. yy. C. The C file can be compiled and used by GCC;
Step 3: Use GCC to compile C Programs
Windows GCC is mainly mingw Compiler: http://www.mingw.org/
Configure the environment variable: Path = mingw/bin;
Run gcc-O output.exe Lex. yy. C.
Generate output.exe;
Step 4: Enter output in the command line to execute the EXE
Now the simple Lex program is complete;
The final total file is as follows: