lex demo

来源:互联网 发布:身份证app扫描软件 编辑:程序博客网 时间:2024/05/20 20:22
%{enum {LOOKUP =0,VERB,ADJ,CONJ};int state;int add_word(int type, char *word);int lookup_word(char *word);%}%option noyywrap%%\n{state = LOOKUP;}^VERB{state = VERB;}^ADJ{state = ADJ;}^CONJ{state = CONJ;}.;/*ignore anything else*/[a-zA-Z]+ {/*a normal word , define it or look it up */        if(state != LOOKUP){/* define the current word */add_word(state, yytext);}else{switch(lookup_word(yytext)){case VERB: printf("%s is verb\n",yytext); break;case ADJ:  printf("%s is adj\n",yytext); break;case CONJ: printf("%s is conj\n",yytext); break;default:    printf("oh, i can't recognize it!!\n");break; }}}%%main(){   yylex();}/*define a linked list of words and types*/struct word *word_list; /*first element in word list */extern void *malloc();struct word{char *word_name;int word_type;struct word *next;};int add_word(int type, char *word){if(lookup_word(word) != 0)return 0;/*word not there, allocate a new entry and link it on the list*/struct word *tem;tem = malloc(sizeof(struct word));tem->next = word_list;char *c = malloc(sizeof(char)*(strlen(word)+1));strcpy(c,word);tem->word_name = c;tem->word_type = type;word_list = tem;return 1;}int lookup_word(char *word){struct word *t = word_list;for(;t;t = t->next){    int r = strcmp(word, t->word_name);    if(r ==0)return t->word_type;}return 0;}

0 0
原创粉丝点击