如何在ANTLR中管理可选空格?

时间:2009-10-31 12:02:32

标签: java whitespace antlr

我正在尝试解析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

3 个答案:

答案 0 :(得分:8)

WS : (' ' | '\t')+
     {$channel = HIDDEN;}
   ;

答案 1 :(得分:2)

检查Lexical Analysis with ANTLR,然后搜索以此标题开头的部分

忽略词法分析器中的空格

您需要使用{ ignore=WS; }规则

答案 2 :(得分:1)

我已经设法使用lexer结构,例如:

WS  :   (' ')+ {skip();};

WSOPT   :       (' ')* {skip();};

但不在NEWLINE中。然后在解析器构造中,例如:

num1 num2 NEWLINE;

关键是要删除词法分析器中除NEWLINE之外的所有WS。