2016-10-07 6 views
1

최근 lex를 배우기 시작했고 몇 가지 예제를 시도했습니다. 'a'로 시작하고 숫자와 1D 배열의 수로 끝나는 변수의 수를 계산하려고합니다.lex/flex의 배열 변수, 변수

%{ 
#undef yywrap 
#define yywrap() 1 
#include<stdio.h> 
int count1; 
int count2; 
%} 
%option noyywrap 
%% 

int|char|bool|float" "a[a-z,A-Z,0-9]*[0-9] {count1++;} 
int|char|float|bool" "[a-z,A-Z]+[0-9,a-z,A-Z]*"["[0-9]+"]" {count2++;} 

%% 

void main(int argc,char** argv){ 
FILE *fh; 
    if (argc == 2 && (fh = fopen(argv[1], "r"))) 
     yyin = fh; 
printf("%d %d",count1,count2); 
yylex(); 
} 

내가 'A'로 시작하고 숫자와 1 차원 배열 (2) 숫자로 끝나는 변수 (1) 수를 계산하려합니다. 입력은 "f.c"파일에서옵니다.

//f.c 

#include<stdio.h> 
void main(){ 
    char a; 
    char b; 
    char c; 
    int ab[5]; 
    int bc[2]; 
    int ca[7]; 
    int ds[4]; 

} 

카운트는 모두 제로를 보이고있다 출력은 다음과 같습니다

또한
0 0#include<stdio.h> 
void main(){ 
     a; 
     b; 
     c; 
     ab[5]; 
     bc[2]; 
     ca[7]; 
     ds[4]; 

} 

, 내가 범주 모두에서 가을 그 변수를 계산 어떻게?

답변

2

main에 주문이 잘못되어 있습니다. 매크로를 사용하여 긴 정규 표현식을 더 읽기 쉽게 만들 수도 있습니다. 그래서 당신에 대한 출력 제한하려면 토큰을 전용 당신이 여분의 줄 바꿈을 처리 할 필요가

//f.c 

#include<stdio.h> 
void main(){ 
    111 char a123 
; 
    char a; 
    char b123; 
    char c; 
    222 int ab[5] 
; 
    222 int bc[2] 
; 
    222 int ca[7] 
; 
    222 int ds[4] 
; 

} 
1 4 

출력에서 ​​파일을

%{ 
#undef yywrap 
#define yywrap() 1 
#include<stdio.h> 
    int count1 = 0; 
    int count2 = 0; 
%} 
TYPE int|char|bool|float 
DIGIT [0-9] 
ID [a-z][a-z0-9A-Z]* 
SPACE " " 
%option noyywrap 

%% 

{TYPE}{SPACE}a[a-z0-9A-Z]*{DIGIT} { 
            printf("111 %s\n",yytext); 
            count1++; 
            } 
{TYPE}{SPACE}{ID}"["{DIGIT}+"]"  { 
            printf("222 %s\n",yytext); 
            count2++; 
            } 
%% 
void main(int argc, char **argv) 
{ 
    FILE *fh; 
    if (argc == 2 && (fh = fopen(argv[1], "r"))) { 
    yyin = fh; 
    } 
    yylex(); 
    printf("%d %d\n", count1, count2); 
} 

실행

//f.c 

#include<stdio.h> 
void main(){ 
    char a123; 
    char a; 
    char b123; 
    char c; 
    int ab[5]; 
    int bc[2]; 
    int ca[7]; 
    int ds[4]; 

} 

결과,

%{ 
#undef yywrap 
#define yywrap() 1 
#include<stdio.h> 
    int count1 = 0; 
    int count2 = 0; 
%} 
TYPE int|char|bool|float 
DIGIT [0-9] 
ID [a-z][a-z0-9A-Z]* 
SPACE " " 
%option noyywrap 

%% 

{TYPE}{SPACE}a[a-z0-9A-Z]*{DIGIT} { 
            printf("111 %s\n",yytext); 
            count1++; 
            } 
{TYPE}{SPACE}{ID}"["{DIGIT}+"]"  { 
            printf("222 %s\n",yytext); 
            count2++; 
            } 
. 
\n 
%% 
void main(int argc, char **argv) 
{ 
    FILE *fh; 
    if (argc == 2 && (fh = fopen(argv[1], "r"))) { 
    yyin = fh; 
    } 
    yylex(); 
    printf("%d %d\n", count1, count2); 
} 

utput

111 char a123 
222 int ab[5] 
222 int bc[2] 
222 int ca[7] 
222 int ds[4] 
1 4