在Antlr中的一个lexer规则上使用多个lexer命令

在Antlr中的一个lexer规则上使用多个lexer命令,antlr,lexer,mode,Antlr,Lexer,Mode,我试图在lexer规则上使用多个lexer命令。 我的代码如下所示: LEXER_RULE: something->mode(NUMBER); mode NUMBER; NU: [0-9]+ ->mode(ANOTHER_MODE); //Going into another mode in case the NU rule is used //now leaving the NUMBER mode, in case there is no number written NO_

我试图在lexer规则上使用多个lexer命令。 我的代码如下所示:

LEXER_RULE: something->mode(NUMBER);

mode NUMBER;
NU: [0-9]+ ->mode(ANOTHER_MODE); //Going into another mode in case the NU rule is used

//now leaving the NUMBER mode, in case there is no number written

NO_NUM: ~[0-9]->mode(DEFAULT_MODE);
lexer规则NU只是可选的,所以我必须说明它没有被使用的情况。但是,我也希望跳过NO_NUM中的所有内容。 差不多

NO_NUM:~[0-9]->跳过->模式(默认模式)


我知道我不允许在一个lexer规则上使用多个lexer命令。有人知道其他方法吗?我需要能够以某种方式离开模式。顺便说一句,我不允许使用语义谓词。谢谢

你就快到了!使用逗号插入:

NO_NUM : ~[0-9] -> skip, mode(DEFAULT_MODE);
显然,这会丢弃任何与
~[0-9]
匹配的内容。所以,如果你有这个语法:

ID : [a-zA-Z]+;
...

mode NUMBER;
  NU.    : [0-9]+ -> mode(ANOTHER_MODE);
  NO_NUM : ~[0-9] -> skip, mode(DEFAULT_MODE);

mode ANOTHER_MODE;
  ...
模式编号
中,您遇到
abc
,然后
a
被丢弃,
bc
将成为
ID
。如果您还希望
a
成为
ID
的一部分,则需要执行以下操作:

ID : [a-zA-Z]+;
...

mode NUMBER;
  NU.    : [0-9]+ -> mode(ANOTHER_MODE);
  NO_NUM : ~[0-9] -> more, mode(DEFAULT_MODE);

mode ANOTHER_MODE;
  ...

关于Lexer命令的更多信息:

您甚至解决了我由于跳过第一个符号而遇到的问题。非常感谢你!