解析javacc中的特定行数

发布于 2024-10-01 08:40:32 字数 260 浏览 2 评论 0原文

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

文件示例摘录:

3 // number of lines to follow = 3
1 3 // 1st line
3 5 // 2nd line
2 7 // 3rd line

我想读取数字(本例中为 3),然后仅读取以下 3 行。如果行数较少或较多,我想生成错误。我怎样才能在javacc中做到这一点?

谢谢

I have a file with a specific format that I would like to parse. In this file I have a number on a line which specifies the number of lines to follow it.

example excerpt from the file:

3 // number of lines to follow = 3
1 3 // 1st line
3 5 // 2nd line
2 7 // 3rd line

I want to read the number (3 in this example) and then read the following 3 lines only. If there are less or more lines I want to generate an error. How can I do this in javacc?

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空城仅有旧梦在 2024-10-08 08:40:32

一种方法是:

/* 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;}
}

Lines.parse() : int 方法返回它应该读取的行数与实际读取的行数之间的差异。

像这样生成解析器:

javacc Lines.jj

编译所有类:

java *.java

并向其提供测试数据(test.txt):

3
1 3
3 5
2 7

像这样:

java Lines < test.txt

生成输出:

diff=0

Here's a way:

/* 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;}
}

The Lines.parse() : int method returns the difference between the number of lines it is supposed to read, and the actual number of lines that are read.

Generate the parser like this:

javacc Lines.jj

compile all classes:

java *.java

And feed it your test data (test.txt):

3
1 3
3 5
2 7

like this:

java Lines < test.txt

which produces the output:

diff=0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文