Skip to content

Instantly share code, notes, and snippets.

@celestialphineas
Created March 12, 2018 15:05
Show Gist options
  • Save celestialphineas/2ab84ca3df254bce0f79d61bdfa9edb0 to your computer and use it in GitHub Desktop.
Save celestialphineas/2ab84ca3df254bce0f79d61bdfa9edb0 to your computer and use it in GitHub Desktop.
Lex program for generating a lexer implementing word counting.
%{
/* Example of Lex program to count words in a file. */
#include <stdio.h>
#include <stdlib.h>
/* Numbers of characters, words and lines */
int nchar = 0;
int nword = 0;
int nline = 0;
%}
%%
[a-zA-Z0-9]+ { nchar += strlen(yytext); nword++; }
\n { nchar++; nline++; }
. { nchar++; }
%%
int main(void)
{
yylex();
printf("%d chars, %d words, %d lines\n", nchar, nword, nline);
return 0;
}
@celestialphineas
Copy link
Author

lex wc.l
gcc lex.yy.c -o wc-lfl
cat wc.l | ./wc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment