事例1:flex事例(计算 英文单词个数)
%{
int wordCount = 0;
int numCount = 0;
FILE *pfin = NULL;
FILE *pfin2 = NULL;
%}
chars [A-za-z\_\'\."]
numbers ([0-9])+
delim [" "\n\t]
whitespace {delim}+
words {chars}+
%%
{words} { wordCount++; }
{whitespace} { }
{numbers} { numCount++; }
%%
void main()
{
yyin = fopen ("in.txt", "r");
pfin = yyin;
pfin2 = fopen("in2.txt", "r");
yyout = fopen ("out.txt", "w");
yylex();
printf(" No of words: %d; num:%d\n", wordCount, numCount);
fprintf(yyout, " No of words: %d ; num:%d \n; lineCnt:%d\n", wordCount, numCount, yylineno);
fclose(pfin);
fclose(pfin2);
fclose(yyout);
}
int yywrap(void)
{
if (pfin == yyin)
{
yyin = pfin2;
return 0;
}
return 1;
}
事例2:flex 与 bison 结合(name=age)
name.y
%{
typedef char* string;
%}
%union {
char* pchr;
int nvalue;
}
%token NAME EQ AGE
%type
%type
%type
%%
file : record file
| record
;
record : NAME EQ AGE {
printf("%s is %d years old!!!\n", $1, $3); }
;
%%
int main()
{
yyparse();
return 0;
}
int yyerror(char *msg)
{
printf("Error encountered: %s \n", msg);
return 0;
}
name.lex
%{
#include "./name.tab.h"
#include
#include
#define YY_NO_UNISTD_H 1
%}
char [A-Za-z]
num [0-9]
eq [=]
name {char}+
age {num}+
%%
{name} { yylval.pchr = strdup(yytext); return NAME; }
{eq} { return EQ; }
{age} { yylval.nvalue = atoi(yytext); return AGE; }
%%
int yywrap()
{
return 1;
}
事例3:flex (自己写的一个简单的 加减乘除)
%{
#define YY_NO_UNISTD_H 1
int nValue = 0;
char* pRet;
char* pExp;
char cOpType[20] = "";
char szBuf[1000];
int nTemp = 0;
%}
char ([a-zA-Z])+
delchr [" "\t\n]
optype ['*''+''/''\-']
result {char}+
whitespace {delchr}+
exp ([0-9])+
eq [=]
%%
{result} { printf("%s\n" , yytext); strncpy(szBuf, yytext, sizeof(szBuf));
if ( strcmp(szBuf, "exit") == 0 )
{return 0;
} }
{whitespace} { }
{exp} {
nTemp = atoi(yytext);
printf("%d\n", nTemp);
if (nTemp != 0)
switch(cOpType[0])
{
case '+':
nValue += nTemp;
printf("var=%s; value=%d; nTemp=%d, cOpType=%s, \n", szBuf, nValue, nTemp, cOpType);
break;
case '-':
nValue -= nTemp;
printf("var=%s; value=%d; nTemp=%d, cOpType=%s, \n", szBuf, nValue, nTemp, cOpType);
break;
case '*':
nValue *= nTemp;
printf("var=%s; value=%d; nTemp=%d, cOpType=%s, \n", szBuf, nValue, nTemp, cOpType);
break;
case '/':
nValue /= nTemp;
printf("var=%s; value=%d; nTemp=%d, cOpType=%s, \n", szBuf, nValue, nTemp, cOpType);
break;
default :
nValue = nTemp;
}
cOpType[0] = '\0';
}
{optype} { printf("%s\n" , yytext); strncpy(cOpType,
yytext, sizeof(cOpType)); }
{eq} { };
%%
int main()
{
yylex();
return 0;
}
int yywrap()
{
return 0;
}