我正在尝试解析 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 的一般解释。
EDIT @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
EDIT 显然这已从 V3 中删除: http://www.antlr.org/pipermail/antlr-interest/2007-February/019423.html
最佳答案
WS : (' ' | '\t')+
{$channel = HIDDEN;}
;
关于java - 我如何管理 ANTLR 中的可选空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1654186/