Pergunta

I want to get and print text within double quotes with using Lex.

["]?([A-Z]*[a-z]*[0-9]*)*["]? {
printf("STR(%s ),yytext");
return 1;
}

I used this but something wrong that I can't figure it out.

Example:

Input

"CNG230 ASN1 Average"

Output

STR("CNG230 ASN1 Average")

Example 2:

Input

 "CNG230/492 Global average"

Output

 STR("CNG230/492 Global average")
Foi útil?

Solução

You don't actually say what is wrong with either of your examples, and I am assuming that

printf("STR(%s ),yytext");

is just a typo for

printf("STR(%s )",yytext);

but there are two problems that I can see.

  1. If you've specified your problem correctly, you don't care what's inside the quotes as long as it isn't another quote. So your rule reduces to

    \"[^"]*\" { ... }
    
  2. The default action if no rules match is to echo the input. So you need another rule to consume everything that doesn't match this rule. Place this afterwards:

    .|\n {}
    

Outras dicas

Your primary problem seems to be that your pattern doesn't allow space as a valid character. You also don't need to be quite so complex with your matching:

["]?[A-Za-z0-9 ]*["]? {
    printf("STR(%s)\n", yytext);
    return 1;
}

Note that I've also provided printf() with a value to print, and output a newline at the end so you'll see the information in a timely manner.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top