University of New Brunswick, Faculty of Computer Science

CS4905 Introduction to Compiler Construction

lex Examples

To compile these examples, type
lex name.l
on the command line, where name.l is replaced with the name of your lex input file. Then invoke the C compiler using
cc lex.yy.c -o name -ll
on the command line. By default, lex always produces output to the lex.yy.c file. The output executable file is called name, so to run the program, type
./name < test.txt
where test.txt is the name of an input file.

lex1.l A lexer to print out all numbers in a file (by default lex reads from standard input).

lex2.l A lexer to print out all HTML tags in a file.

lex3.l A lexer to do the word count function of the wc command in UNIX. It prints the number of lines, words and characters in a file. Note the use of definitions for patterns.

lex4.l Classifying tokens as words, numbers or "other".

lex5.l This lexer prints only words followed by punctuation. If the following sentence was the input from standard input:
"I was here", they said.
But were they? I cannot tell.
it will print the words here, said, they, and tell. It will not print the punctuation; only the words.