这个ANTLR工具非常陌生,需要帮助在ANTRL中编写语法规则,用于使用java将纯文本转换/解析为等效.xml文件。 请任何人帮助我。
我根据我的理解尝试了如下方法,它适用于单行(解析器(而不是完整的配置列表(解析器(
下面的ANTLR语法规则是我的语法.g4
grammar MyTest;
acl : 'acl number' INT configList ('#' configList)* ;
configList : config ('n' config)*;
config : line ('n' line)* ;
line : line WORD INT (WORD)+ ((SOURCE_LOW_IP)* |(WORD)* |(SOURCE_LOW_IP)*)+
|WORD INT (WORD)+
;
fragment
DIGIT : ('0'..'9');
INT : [0-9]+ ; // Define token INT as one or more digits
//WORD : [A-Za-z][A-Za-z_-]* ;
WORD : [A-Za-z][A-Za-z_-]* ;
NEWLINE:'r'? 'n' ; // return newlines to parser (is end-statement signal)
WS : [ trn]+ -> skip ; // toss out whitespace
SOURCE_LOW_IP : INT '.' INT '.' INT '.' INT ; // match IPs in parser
配置列表输入示例:
acl number 3001
rule 0 permit ip source any rule 1 permit ip source 172.16.10.1 # rule 2 permit ip source 172.16.10.2 0.0.0.255 rule 3 deny destination any rule 4 deny destination 172.16.10.4 rule 5 deny destination 172.16.10.5 0.0.0.255 # rule 6 permit ip source any destination 172.16.10.6 0.0.0.255 rule 7 permit ip source 172.16.10.7 0.0.0.255 destination 172.16.11.7 #
expected for output format as below( this will be taken care using java once antlr generates .java and other files)
<filterRuleLists> <filterRuleList id='3001'> <filterRule action='ALLOW' protocol='ANY'> <sourceIPRange low='0.0.0.0' high='255.255.255.255' /> <destinationIPRange low='0.0.0.0' high='255.255.255.255' /> <fileLine file='config' startLine='4' stopLine='4' /> </filterRule> <filterRule action='ALLOW' protocol='ANY'> <sourceIPRange low='172.16.10.1' high='172.16.10.1' /> <destinationIPRange low='0.0.0.0' high='255.255.255.255' /> <fileLine file='config' startLine='5' stopLine='5' /> </filterRule> </filterRuleList> </filterRuleLists>
我熟悉解析器生成器,但不是特定的 ANTLR4,所以这是一个最好的猜测: 我强烈怀疑语法规则
configList : config ('n' config)*;
config : line ('n' line)* ;
应重写为
configList : config (NEWLINE config)*;
config : line (NEWLINE line)* ;
作为片段规则
NEWLINE:'r'? 'n' ; // return newlines to parser (is end-statement signal)
将导致任何'n'
字符被处理为NEWLINE
令牌。