Antlr4:以*开头时跳过行,除非第二个字符是
Antlr4: Skip line when it start with * unless the second char is
在我的输入中,以 *
开头的行是注释行,除非它以 *+
或 *-
开头。我可以忽略评论,但需要得到其他评论。
这是我的词法分析器规则:
WhiteSpaces : [ \t]+;
Newlines : [\r\n]+;
Commnent : '*' .*? Newlines -> skip ;
SkipTokens : (WhiteSpaces | Newlines) -> skip;
一个例子:
* this is a comment line
** another comment line
*+ type value
所以,前两行是注释行,我可以跳过。但是我不知道要定义可以捕获最后一行的 lexer/parser 规则。
您的 SkipTokens
词法分析器规则将永远不会匹配,因为规则 WhiteSpaces
和 Newlines
位于它之前。请参阅此问答以了解词法分析器如何匹配标记:
要使其按预期工作,请执行以下操作:
SkipTokens : (WhiteSpaces | Newlines) -> skip;
fragment WhiteSpaces : [ \t]+;
fragment Newlines : [\r\n]+;
什么是 fragment
,查看此问答:What does "fragment" mean in ANTLR?
现在,回答你的问题。您定义了一个 Comment
规则以始终以换行符结尾。这意味着您输入的末尾不能有评论。所以你应该让评论以换行符或 EOF 结束。
像这样应该可以解决问题:
COMMENT
: '*' ~[+\-\r\n] ~[\r\n]* // a '*' must be followed by something other than '+', '-' or a line break
| '*' ( [\r\n]+ | EOF ) // a '*' is a valid comment if directly followed by a line break, or the EOF
;
STAR_MINUS
: '*-'
;
STAR_PLUS
: '*+'
;
SPACES
: [ \t\r\n]+ -> skip
;
当然,这并不要求 *
位于行首。如果需要,请查看此问答:
在我的输入中,以 *
开头的行是注释行,除非它以 *+
或 *-
开头。我可以忽略评论,但需要得到其他评论。
这是我的词法分析器规则:
WhiteSpaces : [ \t]+;
Newlines : [\r\n]+;
Commnent : '*' .*? Newlines -> skip ;
SkipTokens : (WhiteSpaces | Newlines) -> skip;
一个例子:
* this is a comment line
** another comment line
*+ type value
所以,前两行是注释行,我可以跳过。但是我不知道要定义可以捕获最后一行的 lexer/parser 规则。
您的 SkipTokens
词法分析器规则将永远不会匹配,因为规则 WhiteSpaces
和 Newlines
位于它之前。请参阅此问答以了解词法分析器如何匹配标记:
要使其按预期工作,请执行以下操作:
SkipTokens : (WhiteSpaces | Newlines) -> skip;
fragment WhiteSpaces : [ \t]+;
fragment Newlines : [\r\n]+;
什么是 fragment
,查看此问答:What does "fragment" mean in ANTLR?
现在,回答你的问题。您定义了一个 Comment
规则以始终以换行符结尾。这意味着您输入的末尾不能有评论。所以你应该让评论以换行符或 EOF 结束。
像这样应该可以解决问题:
COMMENT
: '*' ~[+\-\r\n] ~[\r\n]* // a '*' must be followed by something other than '+', '-' or a line break
| '*' ( [\r\n]+ | EOF ) // a '*' is a valid comment if directly followed by a line break, or the EOF
;
STAR_MINUS
: '*-'
;
STAR_PLUS
: '*+'
;
SPACES
: [ \t\r\n]+ -> skip
;
当然,这并不要求 *
位于行首。如果需要,请查看此问答: