//文件Name.y
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char* string;
#define YYSTYPE string
%}
%token NAME EQ AGE
%%
file : record file
| record
;
record : NAME EQ AGE {
printf("%s is %s years old!!!\n",$1,$3);}
;
%%
int main()
{
yyparse();
return 0;
}
int yyerror(char *msg)
{
printf("Error encountered:%s \n",msg);
}
//Name.l文件
%{
#include "y.tab.h"
#include <stdio.h>
#include <string.h>
extern char* yylval;
%}
char [A-Za-z]
num [0-9]
eq [=]
name {char}+
age {num}+
%%
{name} {yylval=strdup(yytext);
return NAME;}
{eq} {return EQ;}
{age} {yylval=strdup(yytext);
return AGE;}
%%
int yywrap()
{
return 1;
}
//text.txt
test = 123
編譯鏈接:
$yacc -d Name.y
$lex Name.l
$gcc y.tab.c lex.yy.c
$./a.out < text.txt
輸出:test is 123 years old!!!