前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Go 语言社区】golang的bufio用于内容解析

【Go 语言社区】golang的bufio用于内容解析

作者头像
李海彬
发布2018-03-20 10:37:31
1.5K0
发布2018-03-20 10:37:31
举报
文章被收录于专栏:Golang语言社区

golang提供了io.Reader,也就是读内容,可以从很多地方读,譬如:

代码语言:javascript
复制
// from string.var r io.Reader = strings.NewReader(string("hello, world"))// from bytes.var r io.Reader = bytes.NewReader([]byte("hello, world!"))// from bytes buffer.var r io.Reader = bytes.NewBuffer([]byte("hello, world"))

这个看起来没有啥稀奇的,就是从字符串或者字节读取呗。最后一个bytes.Buffer是写(Write)时增加到末尾,读(Read)时从头开始读的一个对象,就是个缓冲区。

还有一个比较有用的,带缓冲区的io:

代码语言:javascript
复制
// buffer readervar r io.Reader = bufio.NewReader(strings.NewReader(string("hello, world")))

这个是和带缓冲区的写入是对应的。这个类是给网络reader用的,譬如协议解析,需要看看下面几个字节是什么,然后再解析之类的(Peek)。或者写入时,不断将小的bytes写入,最后Flush之类。

另外,bufio.Reader还提供了特殊的读法,譬如读取字符串(因为有缓冲区所以能读得出来)。

代码语言:javascript
复制
// ReadString reads until the first occurrence of delim in the input,
// returning a string containing the data up to and including the delimiter.
// If ReadString encounters an error before finding a delimiter,
// it returns the data read before the error and the error itself (often io.EOF).
// ReadString returns err != nil if and only if the returned data does not end in// delim.
// For simple uses, a Scanner may be more convenient.
func (b *Reader) ReadString(delim byte) (line string, err error) {

对于内容解析,譬如解析下面的json,支持///**/风格的注释,那么就可以用scanner,也就是特定格式的扫描提取:

代码语言:javascript
复制
s := bufio.NewScanner(strings.NewReader("/*block comments*///line comments\n{}"))
s.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error){    // read more.
    return 0,nil,nil})for s.Scan() {
    fmt.Println(s.Text())
}
fmt.Println("err is", s.Err())

只需要判断是否需要的数据是否有满足,譬如//\n是否成对,如果不成对就再读取。这样就大大降低了复杂逻辑了。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2016-02-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档