我可以将字符串作为bufio.ReadString()的分隔符吗?

I have a file which contains multi-line queries. I wanted to read them one by one and print them. Something like :

temp.sql

select * from table1;  
select *  
from table2;

select 1; 

Since i can have multiline queries I wanted to use ; as the delimiter. Is that possible ? Is there a better method that i can use instead of bufio.ReadString ?

firstly, the prototype of bufio.ReadString is

 func (b *Reader) ReadString(delim byte) (line string, err error)

it can only take one byte as arg, so your ; delimiter won't work.

use ; as delimiter instead.

But if you use ReadString(';') it will contain other characters in your results, such as ' '

a example:

package main

import (
    "bufio"
    "fmt"
    "strings"
)

func main() {

    const raw = `select * from table1;  
select *  
from table2;

select 1;`

    br := bufio.NewReader(strings.NewReader(raw))

    var err error
    var s string
    err = nil
    for err == nil {
        s, err = br.ReadString(';')
        if err == nil {
            fmt.Printf("%q", s)
        }

    }

this will get:

"select * from table1;""  
select *  
from table2;""

select 1;"

online test

Solution:

use Scanner may be more convenient, and achieve this as bellow.

ps: ; will be considered as part of words

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
    "bytes"
)

func main() {
    const raw = `select * from table1;  
select *  
from table2;

select 1;`

    scanner := bufio.NewScanner(strings.NewReader(raw))
    scanner.Split(bufio.ScanWords)

    var tmpbuf bytes.Buffer

    for scanner.Scan() {
        w := scanner.Text()
        tmpbuf.WriteString(w)
        if w[len(w)-1] == ';' {
            tmpbuf.WriteString("
")
            fmt.Printf(tmpbuf.String())
            tmpbuf.Reset()
        } else {
            tmpbuf.WriteString(" ")
        }
    }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading input:", err)
    }
}

you will get:

select * from table1;
select * from table2;
select 1;

online test

You can use bufio.Scanner for that: https://golang.org/pkg/bufio/#Scanner See the lines example: https://golang.org/pkg/bufio/#example_Scanner_lines