我对这个 ANTLR 工具非常陌生,需要在 ANTRL 中编写语法规则方面的帮助,以便使用 java 将纯文本转换/解析为等效的 .xml 文件。 请任何人帮助我解决这一问题。
我根据我的理解尝试如下,它适用于单行(解析器),不适用于完整的configList(解析器)
下面的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 : [ \t\r\n]+ -> skip ; // toss out whitespace
SOURCE_LOW_IP : INT '.' INT '.' INT '.' INT ; // match IPs in parser
配置列表的示例输入:
<小时/>
acl number 3001
<p>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
#
</p>
<p>expected for output format as below( this will be taken care using java once antlr generates .java and other files) </p>
<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
标记。
关于java - 如何编写 ANTLR 语法来解析纯文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58485934/