我正在尝试在 Go 中编写一个扫描器来扫描续行,并在返回之前清理行,以便您可以返回逻辑行。因此,给定以下 SplitLine 函数(Play):
func ScanLogicalLines(data []byte, atEOF bool) (int, []byte, error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
i := bytes.IndexByte(data, '\n')
for i > 0 && data[i-1] == '\\' {
fmt.Printf("i: %d, data[i] = %q\n", i, data[i])
i = i + bytes.IndexByte(data[i+1:], '\n')
}
var match []byte = nil
advance := 0
switch {
case i >= 0:
advance, match = i + 1, data[0:i]
case atEOF:
advance, match = len(data), data
}
token := bytes.Replace(match, []byte("\\\n"), []byte(""), -1)
return advance, token, nil
}
func main() {
simple := `
Just a test.
See what is returned. \
when you have empty lines.
Followed by a newline.
`
scanner := bufio.NewScanner(strings.NewReader(simple))
scanner.Split(ScanLogicalLines)
for scanner.Scan() {
fmt.Printf("line: %q\n", scanner.Text())
}
}
我希望代码返回如下内容:
line: "Just a test."
line: ""
line: "See what is returned, when you have empty lines."
line: ""
line: "Followed by a newline."
但是,它在返回第一行后停止。第二次调用 return 1, "", nil
。
任何人有任何想法,或者它是一个错误?