java - 我如何管理 ANTLR 中的可选空格?

标签 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 的一般解释。

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/

相关文章:

java - 如果该方法的参数是编译时不在类路径中的类,则通过反射获取声明的方法

git - 如何摆脱 git 中的虚假更改?

function - 用于定义/调用多参数函数的 ANTLR 语法

使用drawString时无法解析java.lang.CharSequence

java - Tomcat 服务器错误 - 端口 8080 已被使用

security - 密码中应该允许空格字符吗?

c++ - 从 C++ 中的字符串中删除空格

parsing - ANTLR:自定义语法示例的词法错误帮助

antlr - 跳过匹配的词汇元素或标记的部分

java - 在 Java 的接口(interface)中定义类的能力的实际方面?