参考IBM上的教程:Yacc 与 Lex 快速入门
%{
int wordCount = 0;
int numCount = 0;
%}
chars [A-za-z_'."]
numbers ([0-9])+
delim [" "nt]
whitespace {delim}+
words {chars}+
%%
{words} { wordCount++; /*increase the word count by one*/ }
{whitespace} { /* do nothing*/ }
{numbers} { numCount++; }
%%
int main()
{
yylex(); /* start the analysis*/
printf(" No of words: %dn
", wordCount);
printf(" No of numCount: %dn
", numCount);
}
int yywrap()
{
return 1;
}
保存为wordCount.lex
执行:flex wordCount.lex 生成flex.yy.c
执行:gcc lex.yy.c -lfl -o wordCount生成wordCount
测试:
dhn@dhn-Lenovo-M495:~/tem$ cat input
9a hello world 123 bao niu baojiu
dhn@dhn-Lenovo-M495:~/tem$ cat input | ./wordCount
No of words: 6n
No of numCount: 2n