0

What is the best method to implement a system for parsing a configuration file based on a set of rules? I would appreciate any pointers in the direction of best practices or existing implementations.

Edit: I have not decided not choice of any specific language yet but I am comfortable with both Perl and Python. The files are something along Router/Switch configuration files with different functional sections.

4

3 回答 3

2

假设这不是基于 XML 的配置文件,我可以推荐 ANTLR吗?

  • 根据您提供的 EBNF 样式语法规则文件生成解析器代码。
  • 具有规则文件的图形编辑器作为 Eclipse 插件。
  • 非常强大和健全的解析器技术
  • 灵活地处理解析后的输出
  • 运行时环境允许在 C++、C、C#、Java、Python 和 Ruby 应用程序中使用 ANTLR 进行解析。
于 2009-05-08T20:43:59.180 回答
0

如果您正在考虑 XML 并使用 Java,您可以尝试我的 XML 解析器生成器 ANTXR,它基于 ANTLR 2.7.x

详见http://javadude.com/tools/antxr/index.html _

一个例子:

XML 文件:

<?xml version="1.0"?>
<people>
  <person ssn="111-11-1111">
    <firstName>Terence</firstName>
    <lastName>Parr</lastName>
  </person>
  <person ssn="222-22-2222">
    <firstName>Scott</firstName>
    <lastName>Stanchfield</lastName>
  </person>
  <person ssn="333-33-3333">
    <firstName>James</firstName>
    <lastName>Stewart</lastName>
  </person>
</people>

解析器骨架:

header {
package com.javadude.antlr.sample.xml;
}

class PeopleParser extends Parser;

document
  : <people> EOF;

<people>
  : (<person>)*
  ;

<person> 
  : ( <firstName>
    | <lastName>
    )*
  ;

<firstName>
  : PCDATA
  ;

<lastName>
  : PCDATA
  ;

一个实际处理数据的解析器:

header {
package com.javadude.antlr.sample.xml;

import java.util.List;
import java.util.ArrayList;
}

class PeopleParser extends Parser;


document returns [List results = null]
  : results=<people> EOF
  ;

<people> returns [List results = new ArrayList()]
  { Person p; }
  : ( p=<person>  { results.add(p); }   )*
  ;

<person> returns [Person p = new Person()]
  { String first, last; }
  : ( first=<firstName>  { p.setFirstName(first); }
    | last=<lastName>    { p.setLastName(last);   }
    )*
  ;

<firstName> returns [String value = null]
  : pcdata:PCDATA { value = pcdata.getText(); }
  ;

<lastName> returns [String value = null]
  : pcdata:PCDATA { value = pcdata.getText(); }
  ;

我已经使用它多年了,当我在工作中向人们展示它时,在最初的“习惯语法”学习曲线之后,他们真的很喜欢它。

请注意,您可以使用 SAX 或 XMLPull 前端(如果您愿意,前端可以进行验证)。运行解析器的代码看起来像

// Create our scanner (using a simple SAX parser setup)
BasicCrimsonXMLTokenStream stream =
    new BasicCrimsonXMLTokenStream(new FileReader("people.xml"),
                                   PeopleParser.class, false, false);


// Create our ANTLR parser
PeopleParser peopleParser = new PeopleParser(stream);

// parse the document
peopleParser.document();
于 2009-05-11T20:32:44.800 回答
0

我经常将 YAML 用于配置文件,它是轻量级的,并且有大量的库以不同的语言支持它。

http://www.yaml.org/

于 2009-05-09T14:42:41.310 回答