What I have to write instead of
identifier [a-zA-Z0-9]+
in order to accept also a string done by only numbers?
I wrote new bison and flex files in order to make clear my issue. Bison File:
%{
#include <stdio.h>
#include <string>
using namespace std;
extern int yylex();
extern void yyerror(char*);
%}
//Symbols
%union
{
double double_val;
char *str_val;
};
%token START
%token STOP
%token BEGIN_NUM
%token END_NUM
%token BEGIN_STRING
%token END_STRING
%token <double_val> NUMBER
%token <str_val> IDENTIFIER
%start MyTest
%%
MyTest:
START Block STOP
;
Block:
/* empty */
| Block BEGIN_STRING IDENTIFIER END_STRING { printf("received string: %s \n", $3); }
| Block BEGIN_NUM NUMBER END_NUM { printf("received number: %f \n", $3); }
;
%%
Flex file:
%{
#include <string>
#include "test.tab.h"
void yyerror(char*);
int yyparse(void);
%}
blanks [ \t\n]+
identifier [a-zA-Z0-9]+
number [0-9][0-9]*(.[0-9]+)?
%%
{blanks} { /* ignore */ };
"<test>" return(START);
"</test>" return(STOP);
"<string>" return(BEGIN_STRING);
"</string>" return(END_STRING);
"<num>" return(BEGIN_NUM);
"</num>" return(END_NUM);
{number} { yylval.double_val = atof(yytext);
return(NUMBER);
}
{identifier} {
yylval.str_val=strdup(yytext);
return(IDENTIFIER);
}
%%
void yyerror (char* str){ printf (" ERROR : Could not parse! %s\n", str );}
int yywrap (void){ }
int main(int num_args, char** args){
if(num_args != 2) {printf("usage: ./parser filename\n"); exit(0);}
FILE* file = fopen(args[1],"r");
if(file == NULL) {printf("couldn't open %s\n",args[1]); exit(0);}
yyin = file;
yyparse();
fclose(file);
}
Everything is working when I give in input this file:
<test>
<num>1</num>
<string>eeeeee</string>
<num>2</num>
<string>cccc</string>
<num>3</num>
<num>4</num>
<string>asaa</string>
<string>dsa</string>
</test>
But if I change one field of string with a value with only digits like:
<string>323</string>
I get syntax error...