2015-01-13 88 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