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

Vik*_*dor 6 java antlr4

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

grammar SampleConfig;

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

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

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

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());
Run Code Online (Sandbox Code Playgroud)

这将打印以下输出:

3: key="valuewithspacesinbetween"
Run Code Online (Sandbox Code Playgroud)

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

3: key="value with spaces in between"
Run Code Online (Sandbox Code Playgroud)

是否可以更正语法来实现此行为,还是应该覆盖CommonTokenStream以在解析过程中忽略空格?

Bar*_*ers 6

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

删除跳过命令或制定string词法分析器规则:

STRING : '"' ( '\\' [\\"] | ~[\\"\r\n] )* '"';
Run Code Online (Sandbox Code Playgroud)