Parsing 如何在ANTLR4中不需要空格

Parsing 如何在ANTLR4中不需要空格,parsing,antlr4,context-free-grammar,text-parsing,lexical-analysis,Parsing,Antlr4,Context Free Grammar,Text Parsing,Lexical Analysis,我正在使用ANTLR4尝试分析以下文本: ex1, ex2: examples var1,var2,var3: variables 由于第二行逗号后没有空格,因此无法正确解析。如果我加上空格,它就会工作。我当前用于分析此内容的规则: line : list ':' name; list : listitem (',' listitem)*; listitem : [a-zA-Z0-9]+; name : [a-zA-Z0-9]+; 这非常适用于像第1行这

我正在使用ANTLR4尝试分析以下文本:

ex1, ex2: examples             
var1,var2,var3: variables      
由于第二行逗号后没有空格,因此无法正确解析。如果我加上空格,它就会工作。我当前用于分析此内容的规则:

line : list ':' name;
list : listitem (',' listitem)*;
listitem : [a-zA-Z0-9]+;
name : [a-zA-Z0-9]+;
这非常适用于像第1行这样的行,但在像第2行这样的行上失败了,如果有括号或几乎任何标点符号,它需要标点符号后面有一些空格,我不能总是保证输入的空格


有人知道如何解决这个问题吗

首先添加显式lexer规则(以大写字母开头)。然后为空白添加lexer规则并忽略空白:

 line : list ':' name;
 list : listitem (',' listitem)*;
 listitem : Identifier;
 name : Identifier;


 Identifier : [a-zA-Z0-9]+; // only one lexer rule for name and listitem, since and Identifier may be a name or listitem depending only on the position

 WhiteSpace : (' '|'\t') -> skip;
 NewLine : ('\r'?'\n'|'\r') -> skip; // or don't skip if you need it as a statement terminator 

好的,谢谢,这很有帮助。你能给我解释一下不同的资本化规则之间的区别吗?我没有意识到这有什么不同……Lexer规则以大写字母开始,解析器规则以小写字母开始。Lexer创建令牌,解析器收集令牌。看看语法示例和/或阅读本书。