As a beginner, when I was learning ANTLR4 from the The Definitive ANTLR 4 Reference book, I tried to run my modified version of the exercise from Chapter 7:
/**
* to parse properties file
* this example demonstrates using embedded actions in code
*/
grammar PropFile;
@header {
import java.util.Properties;
}
@members {
Properties props = new Properties();
}
file
:
{
System.out.println("Loading file...");
}
prop+
{
System.out.println("finished:
"+props);
}
;
prop
: ID '=' STRING NEWLINE
{
props.setProperty($ID.getText(),$STRING.getText());//add one property
}
;
ID : [a-zA-Z]+ ;
STRING :(~[
])+; //if use STRING : '"' .*? '"' everything is fine
NEWLINE : '
'?'
' ;
Since Java properties are just key-value pair I use STRING
to match eveything except NEWLINE
(I don't want it to just support strings in the double-quotes). When running following sentence, I got:
D:AntlrExPropFileProp1>grun PropFile prop -tokens
driver=mysql
^Z
[@0,0:11='driver=mysql',<3>,1:0]
[@1,12:13='
',<4>,1:12]
[@2,14:13='<EOF>',<-1>,2:14]
line 1:0 mismatched input 'driver=mysql' expecting ID
When I use STRING : '"' .*? '"'
instead, it works.
I would like to know where I was wrong so that I can avoid similar mistakes in the future.
Please give me some suggestion, thank you!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…