ANTLR4:忽略输入中的空格但不忽略字符串文字中的空格

ANTLR4: ignore white spaces in the input but not those in string literals

我有一个简单的语法如下:

grammar SampleConfig;

line: ID (WS)* '=' (WS)* string;

ID: [a-zA-Z]+;
string: '"' (ESC|.)*? '"' ;
ESC : '\"' | '\\' ; // 2-char sequences \" and \
WS: [ \t]+ -> skip;

输入中的空格被完全忽略,包括字符串文字中的空格。

final String input = "key = \"value with spaces in between\"";
final SampleConfigLexer l = new SampleConfigLexer(new ANTLRInputStream(input));
final SampleConfigParser p = new SampleConfigParser(new CommonTokenStream(l));
final LineContext context = p.line();
System.out.println(context.getChildCount() + ": " + context.getText());

这将打印以下输出:

3: key="valuewithspacesinbetween"

但是,我希望保留字符串文字中的空格,即

3: key="value with spaces in between"

是否可以更正语法以实现此行为,或者我是否应该重写 CommonTokenStream 以在解析过程中忽略空格?

您不应期望解析器规则中有任何空格,因为您在词法分析器中跳过了它们。

要么删除跳过命令,要么使 string 成为词法分析器规则:

STRING : '"' ( '\' [\"] | ~[\"\r\n] )* '"';