我有一个简单的语法如下:
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] )* '"';
关于java - ANTLR4:忽略输入中的空格但不忽略字符串文字中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27915012/