Programming Gems::flex
Материал из NNLUG Wiki.
[править]
flex
Проверка парности скобок
flex -o code.c code.y gcc -o code code.c -ll echo "2+(2+2)))" | ./code
int nm = 0, np = 0;
int nErrors = 0;
#define EOS " "
%%
-[0-9]+ { printf("%s"EOS, yytext); };
[0-9]+ { printf("%s"EOS, yytext); }
"+" { printf("PLUS"EOS); }
"-" { printf("MINUS"EOS); }
"(" { np = np + 1; printf("OPEN"EOS); }
")" { nm = nm + 1; printf("CLOSE"EOS);
if (nm > np) {
nErrors = nErrors+1;
}
}
"\r" { printf("[RET]"EOS); }
"\n" { printf("[EOL]"EOS); }
<<EOF>> { printf("[EOF]"EOS); return 0; }
%%
int main () {
yylex();
if (nm != np) {
printf("Non-completed: %d errors\n",(nErrors==0?1:nErrors));
}
else {
printf("Completed\n");
}
return 0;
}

