我正在尝试解析 ANTLR 中的数据文件 - 它具有可选的空格,例如
3 6
97 12
15 18
下面显示了行的开始和结束位置。最后有一个换行符,没有制表符。
^ 3 6$
^ 97 12$
^ 15 18$
^
我的语法是:
lines : line+;
line : ws1 {System.out.println("WSOPT :"+$ws1.text+":");}
num1 {System.out.println("NUM1 "+$num1.text);}
ws2 {System.out.println("WS :"+$ws2.text+":");}
num2 {System.out.println("NUM2 "+$num2.text);}
NEWLINE
;
num1 : INT ;
num2 : INT ;
ws1 : WSOPT;
ws2 : WS;
INT : '0'..'9'+;
NEWLINE : '\r'? '\n';
//WS : (' '|'\t' )+ ;
WS : (' ')+ ;
WSOPT : (' ')* ;
这使
line 1:0 mismatched input ' ' expecting WSOPT
WSOPT :null:
NUM1 3
WS : :
NUM2 6
line 2:0 mismatched input ' ' expecting WSOPT
WSOPT :null:
NUM1 97
WS : :
NUM2 12
BUILD SUCCESSFUL (total time: 1 second)
(即没有识别出领先的 WS 并且错过了最后一行)。
我想解析没有空格开头的行,例如:
^12 34$
^ 23 97$
但我随后收到错误,例如:
line 1:0 required (...)+ loop did not match anything at input ' '
我很欣赏在 ANTLR 中解析 WS 的一般解释。
编辑@jitter 有一个有用的答案 -{ignore=WS}
没有出现在我正在使用的“权威 ANTLR 参考”书中,因此这显然是一个棘手的领域。
仍然需要帮助 我已将其修改为:
lines : line line line;
line
options { ignore=WS; }
:
ws1 {System.out.println("WSOPT :"+$ws1.text+":");}
num1 {System.out.println("NUM1 "+$num1.text);}
ws2 {System.out.println("WS :"+$ws2.text+":");}
num2 {System.out.println("NUM2 "+$num2.text);}
NEWLINE
;
但得到错误:
illegal option ignore
编辑显然这已从 V3 中删除: http ://www.antlr.org/pipermail/antlr-interest/2007-February/019423.html