微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 如何在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

解决方法

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

原文地址:https://www.jb51.cc/java/120655.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐