作为一个初学者,当我从The Definitive ANTLR 4 Reference书学习ANTLR4,我试图从第7章运行我练习的修改后的版本:ANTLR的:初学者的不匹配输入期待ID
/**
* 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:\n"+props);
}
;
prop
: ID '=' STRING NEWLINE
{
props.setProperty($ID.getText(),$STRING.getText());//add one property
}
;
ID : [a-zA-Z]+ ;
STRING :(~[\r\n])+; //if use STRING : '"' .*? '"' everything is fine
NEWLINE : '\r'?'\n' ;
由于Java性能只是键值对我使用STRING
来匹配除了NEWLINE
(我不希望它只支持双引号中的字符串)。当运行下面的句子,我得到:
D:\Antlr\Ex\PropFile\Prop1>grun PropFile prop -tokens
driver=mysql
^Z
[@0,0:11='driver=mysql',<3>,1:0]
[@1,12:13='\r\n',<4>,1:12]
[@2,14:13='<EOF>',<-1>,2:14]
line 1:0 mismatched input 'driver=mysql' expecting ID
当我使用STRING : '"' .*? '"'
相反,它的工作原理。
我想知道我错在哪里,以便将来避免类似的错误。
请给我一些建议,谢谢!
因为ID也会匹配字符串值,如果我想允许字符串作为值,但不是在双引号,如何做到这一点? – wangdq