是否可以在ANTLR4中定义语法,以识别允许使用空格的文本中的关键字,例如:
First goal refinedInto Goal two, Goal three
Another goal refinedInto ...
这里" refineInto"是一个关键字。到目前为止,我已经提出了以下解析器和词法分析器,但不要认为它是解决我的问题的正确方法。也就是因为我的REF_LEFT标记为我上面的例子评估了" First goal refinedInto"我想分开"第一个目标"来自" refineInto"关键字。
这是我的解析器:
parser grammar GParse;
parse
: REF_LEFT ( STRING COMMA )* STRING EOF
;
这里是lexer:
lexer grammar GLex;
REF_LEFT: [a-zA-Z ]+? 'refinedInto ' -> pushMode(RDef);
mode RDef;
STRING : [a-zA-Z ]+;
COMMA : ',' ' '*;
NL : ('\n' | EOF) -> popMode;
解决这个问题的正确方法是什么?
答案 0 :(得分:0)
是的,您可以采取几种不同的方法。最直接的是让lexer规则使用可能的空格作为关键字文字文本的一部分。如果需要,调整以包括制表符和新行。
RDef_To : 'redefinedInto'
| 'redefined' SPACES 'Into'
;
Ws: ( SPACES | TABS ) -> channel(HIDDEN) ; // should work with 'skip' too
Term: NLINES ; // if used as the record terminator.
fragment NLINES: ( '\r'? '\n' )+ | '\f'+ ;
fragment SPACES: ' '+ ;
fragment TABS: '\t'+ ;