【问题标题】:How to set priorities to rules?如何为规则设置优先级?
【发布时间】:2013-10-10 10:38:31
【问题描述】:

我已经写了规则,但我不明白为什么欲望规则不匹配,因为文档是这样说的:

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

【问题讨论】:

  • 避免对ANY_CHAR 使用* 量词。由于ANY_CHAR 匹配空白字符,因此您匹配的字符串可能比您意识到的要长。 &lt;V_TYPE&gt;{ANY_CHAR} { printf("print Other"); exit(1);} 应该为您服务。
  • David Gorsline我按照你说的做了,但是没用

标签: c lex rules flex-lexer lexical-analysis


【解决方案1】:

如果您的输入确实在两个不同的行上,那么您的 ANY_CHAR 规则与换行符匹配。如果您不关心换行符,则应忽略它们。根据 David Gorsline 的 cmets,我还建议在 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);}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    相关资源
    最近更新 更多