質問

I have written the rules, but I didn't understand why desires rules is not matches, because documentation said this:

When the generated scanner is run, it analyzes its input looking for strings 
which match any of its patterns. If it finds more than one match, it takes the 
one matching the most text (for trailing context rules, this includes the length 
of the trailing part, even though it will then be returned to the input). If it 
finds two or more matches of the same length, the rule listed first in the flex 
input file is chosen.

Also I have seen this answer, but it not helped: Is it possible to set priorities for rules to avoid the "longest-earliest" matching pattern?

 ...
 ANY_CHAR .
 ...

 %%
 "gago"                         { BEGIN V_TYPE; }
 <V_TYPE>"If"                   { printf("print If");       exit(1);}
 <V_TYPE>"Then"                 { printf("print Then");     exit(1);}
 <V_TYPE>"Endif"                { printf("print Endif");    exit(1);}
 <V_TYPE>"While"                { printf("print While");    exit(1);}
 <V_TYPE>"EndWhile"             { printf("print EndWhile"); exit(1);}
 <V_TYPE>{ANY_CHAR}*            { printf("print Other");    exit(1);}

simple input:

gago
EndWhile

Desired output:

print EndWhile

Actual output:

print Other
役に立ちましたか?

解決

If your input is really on two different lines, then your ANY_CHAR rule is matching the newline character. If you don't care about newlines, you should ignore them. I'd also recommend dropping the * modifier on ANY_CHAR as per David Gorsline's comments.

...
ANY_CHAR .
NEW_LINE [\n\r]
...

%%
"gago"                         { BEGIN V_TYPE; }
<V_TYPE>"If"                   { printf("print If");       exit(1);}
<V_TYPE>"Then"                 { printf("print Then");     exit(1);}
<V_TYPE>"Endif"                { printf("print Endif");    exit(1);}
<V_TYPE>"While"                { printf("print While");    exit(1);}
<V_TYPE>"EndWhile"             { printf("print EndWhile"); exit(1);}
<V_TYPE>{NEW_LINE}+            { /* ignore */  }
<V_TYPE>{ANY_CHAR}             { printf("print Other");    exit(1);}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top