去 - 如何创建一个解析器 [英] Go - How to create a parser

查看:175
本文介绍了去 - 如何创建一个解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想解析的样本字符串

  {key1 = value1 | key2 = {key3 = value3} | key4 = {key5 = {key6 = value6}}} 

我希望得到一个类似的输出到一个嵌套的地图

  map [key1] = value1 
map [key2] =(map [key3] = value3 )
map [key4] =(map [key5] =(map [key6] = value6))

这怎么能做到?我是否朝着错误的方向发展?解析方案

编写解析器是一个复杂的话题,它太大而无法覆盖单个答案。



Rob Pike发表了一篇精彩的演讲,讲述了如何在Go中编写词法分析器(这是解析器的一半): http://www.youtube.com/watch?v=HxaD_trXwRE



您还应该看看在例如Go标准库中的解析器代码,了解如何执行此操作的示例: http://golang.org/src /pkg/go/parser/parser.go



在互联网上解析也有大量资源。他们可能有其他语言的例子,但它只是将语法翻译成Go的问题。



我推荐阅读递归下降解析(例如 http://www.cs.binghamton.edu/~zdu/parsdemo/recintro.html )或自顶向下解析(例如 http://javascript.crockford.com/tdop/tdop.html http://effbot.org/zone/simple-top-down-parsing.htm )。


I want to build a parser but have some problems understanding how to do this.

Sample string I would like to parse

{key1 = value1 | key2 = {key3 = value3} | key4 = {key5 = { key6 = value6 }}}

Preferably I would like to get an output similar to a nested map

map[key1] = value1
map[key2] = (map[key3] = value3)
map[key4] = (map[key5] = (map[key6] = value6))

How could this be done? Am I aiming in the wrong direction?

解决方案

Writing a parser is a complicated topic that is too big to cover in a single answer.

Rob Pike gave an excellent talk that walks through writing a lexer (which is a half of the parser) in Go: http://www.youtube.com/watch?v=HxaD_trXwRE

You should also look at e.g. parser code in Go standard library for an example on how to do it: http://golang.org/src/pkg/go/parser/parser.go

There's also plenty resources on parsing on the internet. They might have examples in other languages but it's just a matter of translating the syntax to Go.

I recommend reading up on recursive descent parsing (e.g. http://www.cs.binghamton.edu/~zdu/parsdemo/recintro.html) or top down parsing (e.g. http://javascript.crockford.com/tdop/tdop.html, http://effbot.org/zone/simple-top-down-parsing.htm).

这篇关于去 - 如何创建一个解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆