参考链接: Lex使用指南
下载
要求
实现C-语言词法分析器,每个Token以<名称,属性值>打印,有5种Tokens,最后通过示例程序验证
示例程序
/*A program to perform Euclid'sAlgorithm to compute gcd. */int gcd (int u,int v){if (v==0) return u;else return gcd(v, u-u/v*v);/*u-u/v*v == u mod v */}void main(void){int x;int y;x = input();y = input();output(gcd(x,y));}
实现
新建lex.l文件进行编辑
%{#include<stdio.h>%}delim [ \t\n]ws {delim}+letter [A-Za-z]digit [0-9]id {letter}{letter}*num {digit}{digit}*comments "/*"([^\*]|(\*)*[^\*/])*(\*)*"*/"%%{ws}else |if |int |return |void |while {printf("<keyword, %s>\n", yytext);}{id} {printf("<ID, %s>\n", yytext);}{num} {printf("<NUM, %s>\n", yytext);}{comments} {printf("<COMMENTS, %s>\n", yytext);}"+" |"-" |"*" |"/" |"<" |"<=" |"==" |">" |">=" |"!=" |"=" |";" |"," |"'" |"(" |")" |"[" |"]" |"{" |"}" {printf("<symbol, %s>\n", yytext);}%%int main(){if ((yyin = fopen("./gcd.c","r"))==NULL){printf("Can't open file!\n");return 1;}yylex();return 0;}
最复杂处为/…/注释的匹配,参考: Lex识别C风格字符串和注释

