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
开发者_StackOverflow社区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
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
精彩评论