Parsing 在javacc中解析特定数量的行

Parsing 在javacc中解析特定数量的行,parsing,javacc,Parsing,Javacc,我有一个特定格式的文件要解析。在这个文件中,我在一行上有一个数字,它指定了跟随它的行数 文件摘录示例: 3 // number of lines to follow = 3 1 3 // 1st line 3 5 // 2nd line 2 7 // 3rd line 我想读取数字(本例中为3),然后只读取以下3行。如果有更少或更多的行,我想生成一个错误。如何在javacc中实现这一点 谢谢这里有一个方法: /* file: Lines.jj */ options { STATIC =

我有一个特定格式的文件要解析。在这个文件中,我在一行上有一个数字,它指定了跟随它的行数

文件摘录示例:

3 // number of lines to follow = 3
1 3 // 1st line
3 5 // 2nd line
2 7 // 3rd line
我想读取数字(本例中为3),然后只读取以下3行。如果有更少或更多的行,我想生成一个错误。如何在javacc中实现这一点

谢谢

这里有一个方法:

/* file: Lines.jj */
options {
    STATIC = false ;
}

PARSER_BEGIN(Lines)

class Lines {
    public static void main(String[] args) throws ParseException, TokenMgrError {
        Lines parser = new Lines(System.in);
        System.out.println("diff="+parser.parse());        
    }
}

PARSER_END(Lines)

SKIP  : { " " }
TOKEN : { <NL : ("\r\n" | "\n" | "\r")> }
TOKEN : { <NUMBER : (["0"-"9"])+> }

int parse() :
{
    int linesToRead = 0;
    int linesRead = 0;
    Token n = null;
}
{
    n = <NUMBER> <NL> {linesToRead = Integer.parseInt(n.image);}
    (
        (<NUMBER>)+ <NL> {linesRead++;} 
    )*
    <EOF>
    {return linesToRead - linesRead;}
}
编译所有类:

java *.java
并将您的测试数据(
test.txt
):

像这样:

javacc Lines.jj
java Lines < test.txt
java Lines < test.txt
diff=0