Sscanf of multiple string fields in golang

huangapple go评论75阅读模式
英文:

Sscanf of multiple string fields in golang

问题

我正在尝试使用sscanf来解析多个字符串字段。以下是一个示例代码片段:

package main

import "fmt"

func main() {
    var name, currency string

    _, err := fmt.Sscanf("transaction benson: dollars", "transaction %s: %s", &name, &currency)

    fmt.Println(err, name, currency)
}

输出结果为:

input does not match format benson: 

程序已退出。
英文:

I am trying to use sscanf to parse multiple string fields. Here is an example code snippet:

package main

import "fmt"

func main() {
        var name, currency string

	_, err := fmt.Sscanf("transaction benson: dollars", "transaction %s: %s", &name, &currency)

	fmt.Println(err, name, currency)
}

The output is

input does not match format benson: 

Program exited.

答案1

得分: 11

%s 是贪婪的,会一直读取到下一个空格,这意味着它会读取冒号。在处理完 %s 后,它尝试扫描冒号,但是等等,冒号已经被读取了,下一个字符实际上是一个空格,而不是冒号!所以它失败了。

在 C 语言中,你可以通过使用 %[^:] 而不是 %s 来解决这个问题,但是似乎 Go 语言不支持这样的写法。你可能需要找到一种在不使用 Sscanf 的情况下解析字符串的方法。

英文:

%s is greedy and gobbles up to the next space, which means it eats up the colon. After processing the %s, it then tries to scan in the colon, but wait, that’s already been consumed, and the next character is actually a space, not a colon! So it fails.

In C you’d get around this by using %[^:] rather than %s, but it appears Go doesn’t support this. You might need to find some way to parse your string without Sscanf.

huangapple
  • 本文由 发表于 2015年8月24日 02:38:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/32170109.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定