| • Science | • People | • Locations | • Timeline |
The structure of a lex file is intentionally similar to that of a yacc file; files are divided up into three parts: a definition section, a rules section, and a C code section. Sections are separated by lines that contain only two percent signs: %%
The definition section is the place to define macros using regular expressions, and also to import header files written in C.
The rules section is the most important section; it associates rules to C statements. When lex sees a patter n in its input matching a given rule, it executes the associated C code. Rules are simply regular expressions, probably containing the macros defined in the definition section.
The C code section contains C statements and functions that are copied verbatim to the generated source file. These statements presumably contain code called by the rules in the rules section. In large programs it is more convenient to place this code in a separate file and link it in at compileA compiler is a computer program that translates a computer program written in one computer language (called the source language into an equivalent program written in another computer language (called the output or the target language . Introduction and h time.
The following is an example input file for the flex version of lex. It recognizes strings of numbers (integers) in the input. Given the input "abc123z.!&*2ghj6", the program will print:
Saw an integer: 123 Saw an integer: 2 Saw an integer: 6 /* * Example lexical analyzer for flex * * Picks out strings of digits (integers) from the input. */ /*** Definition section ***/ %{ /* * Some C code to include the C standard I/O library. * Everything inside the %{ %} brackets is inserted * verbatim into the generated file. */ #includeSee also: the flex lexical analyserThe Flex lexical analyser is a free software alternative to Lex. The description for flex as given by the flex manual. flex is a tool for generating scanners: programs which recognized lexical patterns in text. flex reads the given input files, or its sta
Computer programming tools Unix programs