2015-01-13 66 views
5

我有一个简单的语法如下: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 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忽略解析过程中的空白?

回答

4

由于您在词法分析器中跳过了这些规则,因此不应指望解析器规则中有任何空格。

要么删除忽略命令或使string一个词法规则:

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

去除忽略命令正是我需要的 – raghavsood33