Java ANTLR4:忽略输入中的空格,但不要忽略字符串文本中的空格
我有一个简单的语法如下:Java ANTLR4:忽略输入中的空格,但不要忽略字符串文本中的空格,java,antlr4,Java,Antlr4,我有一个简单的语法如下: 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
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以忽略空白?您不应该在解析器规则中使用空格,因为您正在lexer中跳过它们 删除skip命令或使
字符串成为lexer规则:
STRING : '"' ( '\\' [\\"] | ~[\\"\r\n] )* '"';