2016-10-07 37 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(); 
} 

我試圖計數(1)的開始與「a」和以數字和(2)一維陣列的數目結束的變量數。輸入來自「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錯誤。您也可以使用宏來使長regexes更具可讀性。

%{ 
#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]; 

} 

輸出結果

//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++; 
            } 
. 
\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); 
} 

o utput

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