2013-10-10 2 views
0

Я написал правила, но я не понимаю, почему желаний правил не матчи, потому что документация сказала следующее:Как установить приоритеты для правил?

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. 

Кроме того, я видел этот ответ, но это не помогло: 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);} 

простой ввод:

gago 
EndWhile 

Желаемый результат:

print EndWhile 

Фактический выход:

print Other 
+0

Избегайте использования '*' квантификатора для 'ANY_CHAR'. Поскольку 'ANY_CHAR' соответствует символу пробела, вы можете соответствовать более длинной строке, чем вы понимаете. ' {ANY_CHAR} {printf (" print Other "); exit (1);} 'должен служить вашим целям. –

+0

[David Gorsline] (http://stackoverflow.com/users/86809/david-gorsline) Я сделал то, что вы сказали, но это не сработало –

ответ

1

Если ваш вход действительно на двух разных линиях, то ваше правило ANY_CHAR является соответствие символа новой строки. Если вас не волнуют новые строки, вы должны их игнорировать. Я также рекомендую отказаться от модификатора * на ANY_CHAR в соответствии с комментариями Дэвида Горслина.

... 
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);} 
Смежные вопросы