flex使用

参考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\n", wordCount);
    printf(" No of numCount: %dn\n", 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

posted @ 2015-09-17 10:34  gatsbydhn  阅读(166)  评论(0编辑  收藏  举报